<?php
/**
 * set option for entities page
 * Bookmark edit listing ...
 * TODO need to separate with other module
 * @param $basics
 * @param $mod
 * @return unknown_type
 */
//TODO beem update this funcion (by remove entities)
function gain_entities_set_opt($basics, $mod) {
	global $dd, $db, $cache_user_all;

	$basics['id'] = (int)$basics['id'];
	//set link
	//for add more option
	if ($basics['add_entity_op']) {
		$opt_main = $basics['add_entity_op'];
	}

	//set linked
	$linked = 'index.php?mod='.$_REQUEST['mod'];
	if ($_REQUEST['view']) {
		$linked .= '&view='.$_REQUEST['view'];
		$view = '&view='.$_REQUEST['view'];
	}
	$linked .= $basics['linked'].'&link={link}';
	if ($_REQUEST['id']) {
		$linked .= '&id='.$_REQUEST['id'];
	}
	$linked .= '&ajax=1';
	if ($_REQUEST['link'] != 'add' && $_REQUEST['opt'] != 11) {
		$share_link = ' <a href="index.php?fajax=1&mod=sharelink&displayname='.urlencode($basics['item_display']).'" rel="load" class="entity_tool_box_icon" title="' . msg('share link') . '"><img src="im/share.png"></a>';
		if ($_REQUEST['link'] == 'edit') {
			$linked = str_replace('{link}', 'detail', $linked);
			$opt .= ' <a href="#dontMove" class="entity_tool_box_icon" onclick="load_page_content(\''.$linked.'\',\'#items_details\')" title="'.msg('detail').'"><img src="im/up.png"/></a>';
			$submit_form = ' <input class="button-ico entity_tool_box_icon" type="image" src="im/submit.png" name="opt2" title="'.msg('opt2').'" value="save">';
		} else if (check_permission('modify', $basics['entity'], '', $basics['id']) == 1) {
			//echo '$'.$basics['entity'].'|'.check_permission('modify', $basics['entity'], '', $basics['id']).'$';
			$linked = str_replace('{link}', 'edit', $linked);
			$opt .= ' <a href="#dontMove" class="entity_tool_box_icon" onclick="load_page_content(\''.$linked.'\',\'#items_details\')" title="'.msg('edit').'"><img src="im/edit.png"/></a>';
		}

	} else {
		$submit_form = ' <input class="button-ico entity_tool_box_icon" type="image" src="im/submit.png" name="opt1" value="add" title="'.msg('opt_add').'">';
	}

	$module = gain_entity_get_entity_detail();

	if (array_key_exists($basics['entity'], $module)) {
		//FAV by fw
		$opt_fav = ' ' . fav_icon($basics['entity'], $basics['id'], $basics['item_display'], 'index.php?mod='.$basics['entity'].'&link=detail&id='.$basics['id']);
		//VERIFY by fw
		if ($basics['verify'] == 1) {
			$verify = '{{verify}} ';
		}
	}

	//set default link
	$link_list = '';
	if (isset($_REQUEST['entity'])) {
		$entity_link = $_REQUEST['entity'];
	} else {
		$entity_link = $basics['entity'];
	}

	if ($module[$basics['entity']]['mod_main'] != '') {
		$link_list = 'mod='.$module[$basics['entity']]['mod_main'].'&search_for=' . $entity_link;
	} else if ($_SERVER['QUERY_STRING'] != '') {
		$url_string = explode('&link=', $_SERVER['QUERY_STRING']);
		$link_list .= $url_string[0];
		if ($module[$basics['entity']]) {
			$link_list .= '&search_for=' . $entity_link;
		}
	}

	//change link
	if ($basics['link_list']) {
		$link_list = $basics['link_list'];
	}
	$link_list = str_replace('ajax=1', '', $link_list);
	//$listing = fw_show_title('fw_show_title_listing_div', ' <a href="index.php?'.$link_list.'"><img id="fw_show_title_listing" src="im/listing.png" fw_title="'.msg('listing').'"/></a> ');
	$listing = ' <a href="index.php?'.$link_list.'" class="entity_tool_box_icon" rel="redirect" title="'.msg('listing').'"><img src="im/listing.png"/></a>';

	if ($_REQUEST['id'] == '' || $_REQUEST['popup_id'] != '') {
		$opt = $opt_fav = '';
	}

	//tags
	if ($basics['set_tags'] == 1 && $basics['id'] > 0) {
		//get tags default
		$sql = SQL('SELECT '.$basics['entity'].'_tags
		FROM '.$basics['table']. '
		WHERE '.$basics['key'].'=%d', $basics['id']);
		$tags_default = $db->GetOne($sql);
		if (!$tags_default) {
			$tags_default = msg('tag cloud');
		}
		$tags_default = htmlspecialchars(($tags_default));//strip_tags
		//$tags = fw_show_title('fw_show_tags_div', ' <a href="#tags" onclick="fw_entities_tags(\''.$basics['entity'].'\','.$basics['id'].');"><img id="fw_show_tags" src="im/tags.png" fw_title="'.$tags_default.'"/></a> ');
		$tags = ' <a href="index.php?fajax=1&mod=entities&view=tags&entity='.$basics['entity'].'&id='.$basics['id'].'" rel="load" class="entity_tool_box_icon" title="'.$tags_default.'"><img id="fw_show_tags" src="im/tags.png"/></a>';
	}

	if ($basics['id'] > 0) {
		$sql = SQL('SELECT added, added_by, updated, updated_by
		FROM '.$basics['table']. '
		WHERE '.$basics['key'].'=%d', $basics['id']);
		$update_details = $db->GetRow($sql);
		$update_info = msg('entity_update_info');

		$update_info = str_replace('{last_updated_date}', format_date($update_details['updated']), $update_info);
		$update_info = str_replace('{last_updated_by}', $cache_user_all[$update_details['updated_by']]['abbr'], $update_info);

		$update_info = str_replace('{added_date}', format_date($update_details['added']), $update_info);
		$update_info = str_replace('{added_by}', $cache_user_all[$update_details['added_by']]['abbr'], $update_info);

		$updated = '<img src="im/calendar.png" title="'.$update_info.'" class="entity_tool_box_icon"/>';
	}

	if ($basics['open_add'] == 1) {
		return '<span class="tooltip">&nbsp;</span>
		<script type="text/javascript">
			$(document).ready(function(){
				entity_tool_box_ready();
			$("a.fancybox").fancybox();
		});
		</script>' . $listing;
	} else {
		return '<span class="tooltip">&nbsp;</span>
			<script type="text/javascript">
				$(document).ready(function(){
					entity_tool_box_ready();
					$("a.fancybox").fancybox();
				});
			</script>' . $updated . $opt_main . $opt_fav . ' ' . $submit_form . $opt . $listing . $verify . $enews_status . $basics['sp_opt']. ' ' . $tags . $share_link;
	}
}

/**
 * field tags clound
 * Enter description here ...
 * @param $basics
 */
function gain_entities_tags($basics = array()){
	global $db;

	$entity = $basics['entity'];
	$id = $basics['id'];
	if ($_REQUEST['entity']) {
		$entity = $_REQUEST['entity'];
		$id = $_REQUEST['id'];
	}

	if (!$basics) {
		require_once(PATH.'modules/'.$entity.'.php');
		$fn = PREFIX.$entity;
		if (function_exists($fn)) {
			$info = $fn('search_result', 1);
			$basics = $info[$entity]['basics'];
		}
	}

	if ($_REQUEST['link'] == 'update') {
		$param_qry = array(
			'table' => $basics['table'],
			'cols' => array(
				$entity.'_tags', '%s', $_REQUEST['tags'],
			),
			'where' => SQL($basics['key'].'=%d', $id)
		);
		db_query($param_qry);
		exit;
	}

	//get tags default
	$sql = SQL('SELECT '.$entity.'_tags
	FROM '.$basics['table']. '
	WHERE '.$basics['key'].'=%d', $id);
	$tags_default = $db->GetOne($sql);

	//return forms
	$r = '<div style="width: 450px;"><div class="popupHeader">'.msg('tag cloud').'</div>
	<div class="detailsInfo"><span id="tags_updated"></span>'.form_input('test', array('param1' => '380', 'addon_field' => ' id="'.$entity.'_tags_input"', 'default' => $tags_default)).' <input type="button" class="btn medium green awesome btn-add" value="save" style="float: right;" onclick="fw_entities_tags_save(\''.$entity.'\', \''.$id.'\');"/></div>';

	//get tag
	$sql = SQL('SELECT GROUP_CONCAT('.$entity.'_tags)
	FROM '.$basics['table'].'
	WHERE removed IS NULL');
	//AND '.$entity.'_tags IS NOT NULL
	$all_tags = $db->GetCol($sql);
	if ($all_tags) {
		$tags_list = '';
		$tags_array = array();
		foreach ($all_tags as $k => $v) {
			$vx = explode(',', $v);
			if ($vx) {
				foreach ($vx as $k2 => $v2) {
					if ($v2 != '') {
						$v2 = trim($v2);
						$tags_array[$v2] = 1;
					}
				}
			}
		}
	}

	//sort project
	if ($tags_array) {
		$tags_key = array_keys($tags_array);
		natcasesort($tags_key);
		if ($tags_key) {
			foreach ($tags_key as $k => $v) {
				if ($v) {
					$tags_list .= '"' . str_replace("\"", " ", $v) . '",';
				}
			}
		}
	}
	$r .= '<script type="text/javascript">
		$(document).ready(function(){
			var availableTags = ['.$tags_list.'];
			$( "#'.$entity.'_tags_input" )
			.bind( "keydown", function( event ) {
				if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) {
					event.preventDefault();
				}
			})
			.autocomplete({
				minLength: 0,
				source: function( request, response ) {
					// delegate back to autocomplete, but extract the last term
						response( $.ui.autocomplete.filter(
							availableTags, extractLast( request.term )
						)
					);
				},
				focus: function() {
					// prevent value inserted on focus
					return false;
				},
				select: function( event, ui ) {
					var terms = split( this.value );
					// remove the current input
					terms.pop();
					// add the selected item
					terms.push( ui.item.value );
					// add placeholder to get the comma-and-space at the end
					terms.push( "" );
					this.value = terms.join( ", " );
					//save data
					//fw_entities_tags_save(this.value, \''.$entity.'\', \''.$id.'\');
					return false;
				},
				change: function( event, ui ){
					//save data
					//fw_entities_tags_save(this.value, \''.$entity.'\', \''.$id.'\');
				}
			});
		});
	</script></div>';

	return $r;
}

function gain_entities_verify_check_character($text = '', $pattern = '', $type = 1) {
	if ($pattern == '') {
		if ($text == '') {
			return 1;
		}
	} else {
		preg_match_all($pattern, $text, $match);
		
		if (($type == 1 && isset($match[0][0])) || ($type == 2 && !isset($match[0][0]))) {
			return 1;
		}
	}
}

function gain_entities_verify_punctuation($row = array(), $basics){
	//not allow for . & ,
	if ($basics['entity_key'] == 'client') {
		$error_name += gain_entities_verify_check_character($row['name'], '/[\.\,]+/');
	} else {
		$error_name += gain_entities_verify_check_character($row['name'], '/[\,]+/');
	}

	//allow empty, not allow for dot
	if ($row['address_info']) {
		foreach ($row['address_info'] as $k => $v) {
			$error_address += gain_entities_verify_check_character($v['address'], '/\./');
			$error_address += gain_entities_verify_check_character($v['city'], '/\./');
			$error_address += gain_entities_verify_check_character($v['state'], '/\./');
		}	
	}

	//notify place
	if ($error_name == 1 && $error_address > 0) {
		$notify = msg('notify_verify_'.$basics['entity_key'].'_name_and_address');
	} else if ($error_name == 1) {
		$notify = msg('notify_verify_'.$basics['entity_key'].'_name');
	} else if ($error_address > 0) {
		$notify = msg('notify_verify_address');
	}

	return array('error' => $error_name+$error_address, 'notify' => $notify);
}

function gain_entities_verify_phone($row = array(), $basics) {
	global $db;
	if ($row['phone_info']['phone']) {
		foreach ($row['phone_info']['phone'] as $k => $v) {
			$error += gain_entities_verify_check_character($v, '!^(\+|0)[0-9\ ]{6,}$!s', 2);
		}
	}

	if ($error > 0) {
		$notify = msg('notify_verify_phone');
	}
	return array('error' => $error, 'notify' => $notify);
}

function gain_entities_verify_address($row = array(), $basics) {
	global $db;
	$error_address = 0;
	$error_postcode = 0;
	if ($row['address_info']) {
		foreach ($row['address_info'] as $k => $v) {
			//Check if no value, alert
			if (trim($v['address']) == '') {
				++$error_address;
			} else {
				//Check if EACH LINE has more than 45 chars, alert
				$address_line = explode("\n", $v['address']);
				if ($address_line) {
					foreach ($address_line as $l => $v2) {
						if (strlen($v2) > 45) {
							++$error_address;
						}
					}
				}
			}
			
			$error_postcode += gain_entities_verify_check_character($v['postcode']);
		}	
	} else {
		++$error_address;
	}
	
	if ($error_address > 0 && $error_postcode > 0) {
		$notify = msg('notify_verify_address_and_postcode');
	} else if ($error_address > 0) {
		$notify = msg('notify_verify_address');
	} else if ($error_postcode > 0) {
		$notify = msg('notify_verify_postcode');
	}

	return array('error' => $error_address + $error_postcode, 'notify' => $notify);
}

function gain_entities_verify_cloud($row = array(), $basics) {
	//Check if company Name field has word "the" and cloud has no value, then alert
	//Check if Alias Name field has spaces and cloud has no value then alert
	if (stristr($row['name'], 'the') || strstr($row['alias'], ' ')) {
		$error = gain_entities_verify_check_character($row['tags']);
	}

	if ($error == 1) {
		$notity = msg('notify_verify_cloud');
	}

	return array('error' => $error, 'notify' => $notify);
}

function gain_entities_verify_email($row = array(), $basics) {
	//TODO check mail form phone entity!!!
	//check if email field has gmail, hotmail, yahoo, facebook then alert
	if ($row['mail']) {
		$row['phone_info']['mail'][] = $row['mail'];
	}
	if ($row['phone_info']['mail']) {
		foreach ($row['phone_info']['mail'] as $k => $mail) {
			if (strstr($mail, 'hotmail') || strstr($mail, 'gmail') || strstr($mail, 'msn') || strstr($mail, 'yahoo') || strstr($mail, 'facebook')) {
				++$error;
			}
		}
	}

	if ($error > 0) {
		$notify = msg('notify_verify_mail');
	}

	return array('error' => $error, 'notify' => $notify);
}

function gain_entities_verify_user_details($row = array(), $basics) {
	$error = gain_entities_verify_check_character($row['last_name']);
	
	if ($error > 0) {
		$notify = msg('notify_verify_user_details');
	}

	return array('error' => $error, 'notify' => $notify);
}

/**
 * for verify entity record
 * @param $entity
 * @param $type
 * @return unknown_type
 */
function gain_entities_verify($entity = '', $type = ''){
	global $db, $cache_user, $global_config;
	if ($_POST['opt2'] || $entity != '') {
		if ($entity == '' && $_REQUEST['entity']) {
			$entity = $_REQUEST['entity'];
		}
		$table_name = gain_entity_get_entity_detail($entity);
		//update
		$basics['entity'] = $entity;
		$basics['table'] = PREFIX.$table_name['table_name'];
		$basics['key'] = $table_name['field_id'];
		$basics['id'] = $_REQUEST['id'];
		//set verify
		if ($_REQUEST['verify'] == 1) {
			$sql = SQL('UPDATE '.$basics['table'].' SET verified=NOW(), verified_by=%d
			WHERE '.$basics['key'].'=%d', $_SESSION[SESSION_L], $basics['id']);
			fw_log_user_activity($basics, '', 'verified');
			$db->Execute($sql, 'fw');
		}
	
		if ($basics['id'] > 0) {
			$sql = SQL('SELECT verified, verified_by
			FROM '.$basics['table'].'
			WHERE removed IS NULL
			AND '.$basics['key'].'=%d', $basics['id']);
			$row = $db->GetRow($sql, 'fw');
	
			if ($row['verified'] != '') {
				$tools_tip = '';
				if ($_REQUEST['verify'] == 1) {
					$verify_name = $cache_user[$row['verified_by']]['abbr'];
					$tools_tip = '
					<script type="text/javascript">
					$(document).ready(function(){
						$("div.show_options img").mouseover(function(){
							fw_show_popup_title($(this).attr("id"), this);
						}).mouseout(function(){
							$("#"+$(this).attr("id")+"_div").hide();
							$(this).parents("div.show_options").children("span.tooltip").html("&nbsp;");
						});
					});
					</script>';
				} else {
					$verify_name = $cache_user[$row['verified_by']]['abbr'];
				}
				$r = fw_show_title('fw_show_title_verify_div', ' <img src="im/verify_p.png" fw_title="'.$verify_name.' - '.format_date($row['verified']).'" id="fw_show_title_verify"/>').$tools_tip;
			}
		}
	} else {
		if ($entity == '' && $_REQUEST['entity']) {
			$entity = $_REQUEST['entity'];
		}
		$table_name = gain_entity_get_entity_detail($entity);
		$basics['entity'] = $entity;
		$basics['table'] = PREFIX.$table_name['table_name'];
		$basics['key'] = $table_name['field_id'];
		$basics['id'] = $_REQUEST['id'];
		$basics['entity_key'] = $table_name['table_name'];
//		$verify_point = array('punctuation' => msg('verify_punctuation'), 'phone' => msg('verify_phone'), 'address' => msg('verify_address'), 'email' => msg('verify_email'), 'user_details' => msg('verify_user_details'), 'cloud' => msg('verify_cloud'));
		$verify_point = explode(':', $table_name['verify_point']);
		
		if ($verify_point) {
			foreach ($verify_point as $k => $v) {
				if ($v == 'punctuation') {
					$f[$table_name['field_select'] . ' AS name'] = 1;
					$address_info_need = 1;
				} else if ($v == 'email') {
					$f[$table_name['field_email'] . ' AS mail'] = 1;
					$phone_info_need = 1;
				} else if ($v == 'address') {
					$address_info_need = 1;
				} else if ($v == 'cloud') {
					$f[$entity.'_tags AS tags'] = 1;
					$f[$entity.'_tags AS alias'] = 1;
				} else if ($v == 'user_details') {
					$f[$basics['entity_key'].'_name_last AS last_name'] = 1;
				} else if ($v == 'phone') {
					$phone_info_need = 1;
				}
			}
			if ($f) {
				$sql = SQL('SELECT ' . implode(', ', array_keys($f)) .' 
				FROM ' . $basics['table'] . ' 
				WHERE ' . $basics['key'] . '=%d', $basics['id']);
				$row = $db->GetRow(str_replace('&quot;', '"', $sql));
			}

			if ($address_info_need == 1) {
				$sql = SQL('SELECT '.$table_name['address_field_ad'].', address, city, postcode, state
				FROM gain_'.$basics['entity_key'].'_address 
				WHERE '.$basics['key'].'=%d 
				AND removed IS NULL', $basics['id']);
				$row['address_info'] = $db->GetArray($sql);
			}

			if ($phone_info_need == 1) {
				$sql = SQL('SELECT id_phone_type, phone_no
				FROM gain_phone_entity 
				WHERE (entity=%s AND id_entity=%d) OR (entity2="address" AND id_entity2=%d)
				AND id_phone_type IN(5,6,7,9,10,16)', $basics['entity_key'], $basics['id'], $basics['id']);
				$phone_info = $db->GetArray($sql);
				if ($phone_info) {
					foreach ($phone_info as $k => $v) {
						$phone_no = explode('|||', $v['phone_no']);
						
						$phone_type = 'phone';
						//10: direct, 5: hone, 7: fax, 6: office, 9: mobile, 16: mail
						if ($v['id_phone_type'] == 16) {
							$phone_type = 'mail';
						}
						$row['phone_info'][$phone_type][] = $phone_no[0];					
					}
				}
			}
			if (!$row) {
				$fn_txt1 = '<font color="red">please verify sql: "'.$sql.'"</font><br/>';
			}

			foreach ($verify_point as $k => $v) {
				if ($v != '') {
					$verify_icon = 'im/verify_pass.png';
					//check tooltip per item 
					$verify_title = msg('verify');
					$fn = 'gain_entities_verify_' . $v;

					if (function_exists($fn)) {
						$verify_info = $fn($row, $basics);
						if ($verify_info['error'] > 0) {
							$verify_icon = 'im/verify_warning.png';
							$verify_title = $verify_info['notify'];
						}
					} else {
						$fn_txt = '<font color="red">please create function: "'.$fn.'"</font>';
					}

					$verify_content .= $fn_txt.'<br/><img src="'.$verify_icon.'" title="'.$verify_title.'"/> '.str_replace('{cloud}', '<img src="im/tags.png" title="'.msg('tag cloud').'"/>', msg('verify_' . $v)).'<br class="clr"/>';
				}
			}
		}

		$r = '<div class="popupHeader">' . msg('verify details') . '</div>';
		$r .= '<h3>'.msg('verify warning').'</h3>'.$fn_txt1;
		//$r .= nl2br($global_config['system']['verify_some_thoughts']);
		$r .= $verify_content;
		$r .= '
		<form method="post" action="index.php?ajax=1&mod=entities&view=verify&verify=1" id="verify_'.$_REQUEST['entity'].'" style="text-align: right; margin-top: 7px;">
			<input type="hidden" name="entity" value="'.$_REQUEST['entity'].'"/>
			<input type="hidden" name="id" value="'.$_REQUEST['id'].'"/>
			<input type="submit" name="opt2" class="btn medium green awesome btn-add" value="'.msg('verify_confirm').'"> 
			<input type="button" name="cancel" class="btn medium gray awesome btn-cancel" value="'.msg('cancel').'" onclick="closePopup();">
		</form>
		<script type="text/javascript">
			$(document).ready(function(){
				$("#verify_'.$_REQUEST['entity'].'").ajaxForm(function(data){
					$("#items_details").find("div.show_options").css("background","#FFF").css("border","1px solid #6F98CE");
					$("#items_details").find("span.verify_item").html(data);
					$("#verification_notify").closest("tr").remove();
					$("#verification_notify").remove();
					closePopup();
				});
			});
		</script>';
	}
	return $r;
}

/**
 * show confirmation word after add
 * @param $entity
 * @return unknown_type
 * re-act is id item
 * act is action before direct to this page [exam: 4 is removed, 0 is added,
 * for merge re-act=basics[id]&act=5&search_for=entity&
 */
function gain_entities_show_re_act($entity, $type = '') {
	global $cm_menu, $db;
	if ($_REQUEST['link'] == 'detail') {
		return;
	}
	if (isset($_REQUEST['re-act'])) {
		if ($_REQUEST['re-act'] > 0) {
			if ($_REQUEST['act'] == '4') {
				$re_act_linked = msg('record removed');
			} else {
				if ($_REQUEST['act'] == '0') {//added
					$cont = msg('record added, click here to see details');
				} else if ($_REQUEST['act'] == '5') {//merge
					$cont = msg('record merged, click here to see details');
				} else if ($_REQUEST['act'] == '6') {
					$cont = msg('group created, click here to see details');
				} else if ($_REQUEST['act'] == '7') {
					$cont = msg('group updated, click here to see details');
				} else if ($_REQUEST['act'] == '8') {
					//get group name
					$sql = SQL('SELECT group_name FROM gain_fw_entity_group WHERE group_token=%s', $_REQUEST['entity']);
					$group_name = $db->GetOne($sql);
					$cont = msg('Group {group_name} updated');
					$cont = str_replace('{group name}', $group_name, $cont);
				} else {//update
					$cont = msg('record updated, click here to see details');
				}
				$p = 0;
// 				$m = $cm_menu['M'][$entity]['M'];
// 				echo $entity.'|'.$m;
// 				if ($m != '') {
// 					echo in_array($m, $cm_menu['M'][$m]['E']);
// 					if (in_array($m, $cm_menu['M'][$m]['E'])) {
// 						$p = 1;
// 					} else {
// 						$p = 0; 
// 					}
// 				}

				if ($_REQUEST['act'] == 6 || $_REQUEST['act'] == 7 || $_REQUEST['act'] == 8) {
					$re_act_linked = '<a href="index.php?mod='.$_REQUEST['mod'].'&search_for='.$_REQUEST['entity'].'">'.$cont.'</a>';
				} else if ($_REQUEST['mod'] == 'settings') {
					$re_act_linked = '<a href="index.php?mod=settings&view='.$entity.'&link=detail&id='.(int)$_REQUEST['re-act'].'">'.$cont.'</a>';
				} else if ($_REQUEST['mod'] == 'newsletter') {
					$re_act_linked = '<a href="index.php?mod=newsletter&view='.$entity.'&link=detail&id='.(int)$_REQUEST['re-act'].'">'.$cont.'</a>';
				} else if ($p == 1) {
					$re_act_linked = '<a href="index.php?mod='.$m.'&link=detail&id='.(int)$_REQUEST['re-act'].'">'.$cont.'</a>';
				} else if ($_REQUEST['search_for'] == $entity) {
					$re_act_linked = '<a href="index.php?mod='.$entity.'&link=detail&id='.(int)$_REQUEST['re-act'].'">'.$cont.'</a>';
				} else {
					$re_act_linked = '<a href="index.php?mod='.$_REQUEST['search_for'].'&link=detail&id='.(int)$_REQUEST['re-act'].'">'.$cont.'</a>';
				}
			}
		} else {
			if ($entity == $_REQUEST['search_for']) {
				$re_act_linked = msg('record does not exists');
			}
		}

		//$show_act = '<div class="fw-info_error ui-state-default ui-corner-all" style="padding: 0pt 0.7em; margin-top: 20px;">
		//<span class="ui-icon ui-icon-info" style="margin: 7px 0.3em 0pt 0pt; float: left;"></span>'.$re_act_linked.'</div>';
		if ($re_act_linked != '') {
			$show_act = fw_notify_msg($re_act_linked, 'notify', array('un_msg_func' => 1, 'close_element' => 60, 'id' => 're_act_'.$entity));
		}
	}

	$fn = PREFIX.$_REQUEST['mod'].'_'.$_REQUEST['view'].'_validate';
	if (function_exists($fn)) {
		$validate_info = $fn('display', $basics['id']);
	}
	return $show_act.$validate_info;
}

/**
 * set submenu for entity
 * @param $type
 * @return unknown_type
 */
//TODO remove this function
function gain_entity_set_submenu_tmp($type = ''){
	global $sub_menu, $tpl;
	if (strstr($_REQUEST['entity'], 'clients')) {
		$ents = 'clients';
	} else if (strstr($_REQUEST['entity'], 'contacts')) {
		$ents = 'contacts';
	}
	$option = array('search', 'add');
	if ($sub_menu[$ents]) {
		$set_sub = array();
		foreach ($option as $k2 => $v2) {
			if ($v2 == 'add') {
				unset($sub_menu[$ents][$ents.'-'.$ents.'_people']);
			}

			foreach ($sub_menu[$ents] as $k => $v) {
				//1 for edit form or display detail
				if (($_REQUEST['entity'] == $k || ($_REQUEST['search_for'] == $k))) {
					$class = ' style="text-decoration: underline;"';
				} else {
					$class = '';
				}
				if ($v2 == 'add') {
					$linked = 'index.php?mod=entities&entity='.$k.'&link=add';
					$h = msg('add '.$k);
					if ($_REQUEST['link'] != 'add') {
						$class = '';
					}
				} else if ($v2 == 'search') {//search
					$linked = 'index.php?mod=entities&entity='.$ents.','.$ents.'_people&search_for='.$k.'#'.$k.'';
					$h = $v['H'];
					if ($_REQUEST['link'] == 'add') {
						$class = '';
					}
				}

				if (($v2 == 'add' && check_permission('add',trim($k)) == 1) || $v2 == 'search') {
					$set_sub[$v2][$k] = '<a href="'.$linked.'"'.$class.' class="submenu_'.$k.'_'.$v2.'">&raquo; '.$h.'</a>';
				}
			}
		}
		if ($set_sub) {
			foreach ($set_sub as $k => $v) {
				if ($v) {
//					gain_set_submenu('<img src="im/'.$k.'.png" /> ');
					foreach ($v as $k2 => $v2) {
						gain_set_submenu($v2);
					}
				}
			}
		}
	}
}

/**
 *
 * @return unknown_type
 */
function gain_entities_label(){
	return plug_label($_REQUEST['entity'], $_REQUEST['pattern']);
}

/**
 *
 * @return unknown_type
 */
function gain_entities_quick_search(){
	global $db, $ui_theme;
	//set entities display to session
	if ($_REQUEST['ajax'] == 1 && $_REQUEST['entity_qs']) {
		$_SESSION[SESSION_A]['quick_search'][$_REQUEST['entity_qs']] = $_REQUEST['display'];
		exit;
	}
	if (!$ui_theme[$_SESSION[SESSION_A]['theme']]['corner']) {
		$ui_theme[$_SESSION[SESSION_A]['theme']]['corner'] = ' 5px;';
	}
	return '<div style="float: left; margin: 0 6px 0 0; background: #FFF; padding-bottom: 1px;" class="ui-corner-all">'.form_lookup('quick_search_lookup', array('default' => array(0 => 'Quick Search'), 'param2' => array('attr' => 'quick_search', 'list' => 'quick_search_list'), 'addon_field' => ' msg="'.msg('top_label_quick_search').'" placeholder="'.msg('quick_search').'" style="margin-left: '.$ui_theme[$_SESSION[SESSION_A]['theme']]['corner'].'; border: 0; padding: 0.20em 3px 0.20em 25px;"')).' <a href="#profile" style="padding-right: '.$ui_theme[$_SESSION[SESSION_A]['theme']]['corner'].';" onclick="$(\'#quickSearchquick_search\').val(\'\'); show_popup_link(this, \'&ajax=1&mod=profile&quick_search=user_search\', 1, 660);"><img src="im/gear.png" style="padding-top: 6px;" title="'.msg('manage quick search preferences').'"/></a></div>';
}

/**
 *
 * @return unknown_type
 */
function gain_entities_merge(){
	global $db;
	$entity = $_REQUEST['entity'];
	$items = explode(',', $_REQUEST['items']);

	require_once(PATH.'modules/'.$entity.'.php');
	$func_get_entities = PREFIX.$entity;
	$entities = $func_get_entities('', 1);

	//set basics, fields
	$basics = $entities[$entity]['basics'];
	$fields = $entities[$entity]['fields'];
	//set title column(1)
	//cleaned
	$cleanVar = fw_data_cleanup($fields, $basics);
	$fields  = $cleanVar[0];
	$basics  = $cleanVar[1];

	if ($_POST['merge']) {
		foreach ($_POST['keys'] as $key => $id) {
			if ($id == $_POST['items']) {
				unset($fields[$key]);
			} else {
				$get_data_id = $id;
			}
		}

		$basics['id'] = $get_data_id;
		if ($basics['id'] > 0) {
			$fields = fw_data_get($fields, $basics);
			//use form_funct to return query update
			foreach ($fields as $k => $v) {
				if ($v['skip'] != 1) {
					unset($post);
					//run to function
					$func = 'form_'.$v['type'];
					//TODO beem check all type
					//type C,X
					if ($v['type'] == 'city') {
						$post[$k] = $v['default']['city'];
						$post[$v['prefix'].'postcode'] = $v['default']['postcode'];
					} else if ($v['type'] == 'money') {//MONEY
						if ($v['currency'] != 0 || !isset($v['currency'])) {
							$post[$k] = $v['default']['money'];
							$post[$k.'_currency'] = $v['default']['currency'];
						}
					} else if ($v['type'] == 'name') {
						$post[$k] = $v['default'][$k];
						$post[$k . '_first'] = $v['default'][$k . '_first'];
						$post[$k . '_last'] = $v['default'][$k . '_last'];
						$post[$k . '_title'] = $v['default'][$k . '_title'];
						$post[$k . '_middle'] = $v['default'][$k . '_middle'];
						$post[$k . '_initials'] = $v['default'][$k . '_initials'];
						$post[$k . '_suffix'] = $v['default'][$k . '_suffix'];
						$post[$k . '_display'] = $v['default'][$k . '_display'];
						$post[$k . '_keep'] = $v['default'][$k . '_keep'];
					} else if ($v['type'] == 'autocomplete') {
						$post[$k] = $v['default']['id'];
						$post[$k.'_autocomplete'] = $v['default']['name'];
					} else {
						$post[$k] = $v['default'];
					}

					if (function_exists($func)) {
						$post['merge'] = 1;
						$post['id'] = $basics['id'];
						$post['id_item_update'] = $_POST['items'];
						if ($v['type'] == 'file') {
							$a = $func($k, $v, $link = '', 'update', $post);
						} else {
							$a = $func($k, $v, 'update', $post);
						}
						if (trim($a['qry']) != '') {
							$sql_arr[$k] = $a['qry'];
						}
					}
				} else {
					if ($v['type'] == 'E') {
						$func = PREFIX.$k;
						if (function_exists($func)){
							$v['id_item_update'] = $_POST['items'];
							$a = $func($v, 'merge', $basics['id']);//return qry or execute
							if (trim($a['qry']) != '') {
								$sql_arr[$k] = $a['qry'];
							}
						}
					}
				}
			}
			$sql_arr[] = 'updated=NOW()';
			$sql_arr[] = 'updated_by=' . $_SESSION[SESSION_L];
			if ($sql_arr) {
				$sql = 'UPDATE '.$basics['table'].' SET '.implode(', ', $sql_arr).' WHERE '.$basics['key'].'='.$_POST['items'];
				$db->Execute($sql, 'fw');
				$sql = SQl('UPDATE '.$basics['table'].' SET updated=NOW(), updated_by=%d, removed=NOW(), removed_by=%d WHERE '.$basics['key'].'=%d', $_SESSION[SESSION_L], $_SESSION[SESSION_L], $get_data_id);
				$db->Execute($sql, 'fw');
			}
		} else {
			if ($_POST['items_merge']) {
				foreach ($_POST['items_merge'] as $k => $v) {
					if ($k != $_POST['items']) {
						$get_data_id = $k;
					}
				}
				$sql = SQl('UPDATE ' . $basics['table'] . ' SET updated=NOW(), updated_by=%d, removed=NOW(), removed_by=%d WHERE ' . $basics['key'] . '=%d', $_SESSION[SESSION_L], $_SESSION[SESSION_L], $get_data_id);
				$db->Execute($sql, 'fw');
			}
		}

		//update tabs
		$func = PREFIX . $entity . '_merge';
		if (function_exists($func)){
			//send param, id, id_update
			$func($_POST['items'], $get_data_id);
		};

//		header('location: '.$_POST['fw_re-action']);
		$json['complete'] = 1;
		exit(json_encode($json));
	}
	//get data for items select
	if ($items) {
//		$items_show['head'] = 1;
//		$head = '<tr class="ui-state-default hide"><th></th>';
		foreach ($items as $k => $id_item) {
			$item_show[$id_item] = '';
		}
		$items_merge = '';
		foreach ($items as $k => $id_item) {
//			$items_show[$id_item] = 1;
			$items_merge .= '<input name="items_merge['.$id_item.']" type="hidden" value="1"/>';
			$basics['id'] = $id_item;
			//set align
			$align = '';
			if ($k == 0) {
				$align = ' align="right"';
			}

			$fields_entity[$id_item] = fw_data_get($fields,$basics);
			//set $k column($k+1)
			if ($fields_entity[$id_item]) {
				foreach ($fields_entity[$id_item] as $key => $inf) {
					if ($inf['type'] != '' && $inf['type'] != 'head') {
						$h = '';
						//radio
						$radio_param = array('values' => $item_show, 'addon_field' => ' style="padding-right: 50px;"', 'show_label' => 0, 'default' => $items[0], 'force_radio' => 1);
						//$width = ' width="30%"';
						$colspan = '';
						if ($k == 0) {
							$fields_entity[$id_item][$key]['head'] = strip_tags($fields_entity[$id_item][$key]['head']);
							if ($fields_entity[$id_item][$key]['head']) {
								$h = $fields_entity[$id_item][$key]['head'];
							} else if ($fields_entity[$id_item][$key]['vhead']) {
								$h = $fields_entity[$id_item][$key]['vhead'];
							}
							if ($inf['type'] == 'head') {
								$colspan = ' colspan="4"';
								$h = '<strong>'.$h.'</strong>';
							}
							if ($_REQUEST['c']) {
								$check_type = '<br/><i style="color: red;">' . $inf['type'] . '</i>';
							}
							$rf[$key] .= '<td'.$colspan.'>' . $h . $check_type . '</td>';
						} else {
							if ($inf['type'] != 'head') {
								$rf[$key] .= '<td align="center" valign="top" width="70">'.form_radio('keys['.$key.']', $radio_param).'</td>';
							}
						}
						if ($inf['type'] != 'head') {
							$inf['value_only'] = 1;
							$inf['displayonly'] = 1;
							$f = fw_form_item($key, $inf, $basics);
							$hide_field[$key][$basics['id']] = $f;
							$rf[$key] .= '<td' . $align . $width . ' valign="top">' . $f . '</td>';
						}
					}
				}
			}
		}
	}

	//table show
	$enctype = '';
	if ($basics['files'] == 1) {
		$enctype = ' enctype="multipart/form-data"';
	}

	$r = '<div id="items_details" class="div_' . $basics['entity'] . '"><form id="ajax_form_'.$basics['entity'].'" '.$enctype.' action="index.php?ajax=1&mod=entities&view=merge&entity='.$basics['entity'].'" method="post"><input type="hidden" name="items" value="'.$basics['id'].'"/>'.$items_merge;
	$r .= '<table cellpadding="4" cellspacing="1" class="fw-items_list ui-corner-all ui-widget fw-table_effect" width="100%">';
	$j = 0;
	foreach ($fields as $key => $val) {
		$hide_class = '';
		if ($hide_field[$key]) {
			$z = array_values($hide_field[$key]);
			if ($z[0] == '' && $z[1] == '') {
				$hide_class = ' hide';
			}
		}

		$r .= '<tr class="fw-event' . (++$j%2) . $hide_class . '">' . $rf[$key] . '</tr>';
	}
	//show information for tabs
	$func = PREFIX.$basics['entity'].'_merge_info';
	if (function_exists($func)) {
		$merge_info = $func();
	} else {
		$merge_info = $func.'...';
	}

	$entity_info = gain_entity_get_entity_detail($basics['entity']);
	if ($entity_info['mod_main'] != '') {
		$mod = $entity_info['mod_main'];
	} else {
		$mod = $basics['entity'];
	}

	$r .= '<tr><td colspan="2">'.$merge_info.'</td><td colspan="2" align="right" valign="top" style="padding: 10px;"><input type="submit" name="merge" value="'.msg('merge information').'" class="btn medium green awesome"/> '.msg('and').'
	<select name="fw_re-action">
		<option value="index.php?mod='.$basics['entity'].'&link=detail&id='.$basics['id'].'">'.msg('display details').'</option>
		<option value="index.php?mod='.$mod.'&entity='.$basics['entity'].'&search_for='.$entity.'&re-act='.$basics['id'].'&act=5">'.msg('display listing').'</option>
	</select>
	</td></tr></table>';
	$r .= '</form></div>
	<script type="text/javascript">
		$(document).ready(function(){
			$("#ajax_form_'.$entity.'").ajaxForm({
				beforeSubmit: merge_before_submit,
				success: merge_success,
				dataType: "json"
			});

			function merge_before_submit () {
				if (confirm("'.msg('confirm_merge_process').'")){
				';
					if (DISABLE_SUBMIT == 1) {
						$r .= ' fw_disable_submit("'.$entity.'"); ';
					}
					$r .= '
				} else {
					return false;
				}
			}

			function merge_success (data) {
				if (data.complete == 1) {
					var link_direct = $("select[name=fw_re-action]").fieldValue();
					window.location = link_direct;
				}
			}
		});
	</script>
	';
	return $r;
}

function gain_entities_sortable(){
	global $db;
	$entity = $_REQUEST['entity'];
	//get primary field
	require_once(PATH.'modules/settings.php');
	$function = 'gain_settings_'.$entity;
	if (function_exists($function)){
		$rsl = $function('',1);
		$entity_basic = $rsl[$entity]['basics'];
		$entity_field = $rsl[$entity]['fields'];
	}else $r .= 'Function doesn\'t exist';

	//save order
	if ($_REQUEST['save'] == 1) {
		if ($_REQUEST['order']) {
			foreach ($_REQUEST['order'] as $k => $id) {
				$sql = 'UPDATE '.$entity_basic['table'].' SET order_list='.$k.' WHERE '.$entity_basic['key'].'='.$id;
				$db->Execute($sql, 'fw');
			}
		}
		fw_cache($entity_basic['table'], 1);
		exit;
	} else {
		if ($entity_field) {
			foreach ($entity_field as $k => $v) {
				if ($v['primary_field'] == 1) $name_fields[] = $k;
			}
		}
		//get entity list by use primary field(s)
		if ($name_fields) {
			$sql = 'SELECT '.$entity_basic['key'].', CONCAT('.implode('," ",',$name_fields).') AS entity_name
			FROM '.$entity_basic['table'].'
			WHERE removed IS NULL
			ORDER BY order_list';
			$entity_list = $db->GetAssoc($sql, 'fw');
		} else {
			$r .= 'This entity have no primary field';
		}

		//show sortable reorder list
		if ($entity_list) {
			foreach ($entity_list as $k => $v) {
				$entity_order .= '<li style="cursor:move; margin:4px; background:#FFF;" id="order_'.$k.'" onmouseover="$(this).css(\'background\',\'#DDD\');" onmouseout="$(this).css(\'background\',\'#FFF\');">'.clean($v).'</li>';
			}
			$r .= '
			<ul id="entity_order">
				'.$entity_order.'
			</ul>
			<input style="float:right;" class="btn medium green awesome btn-add" type="button" value="'.msg('opt2').'" onClick="reorder_save();"/>
			<br class="clr">';
			$js = '<script type="text/javascript">
					$(document).ready(function(){
						$("#entity_order").sortable();
					});

					function reorder_save(){
						var order = $("#entity_order").sortable("serialize");
						$.post("index.php?ajax=1&mod=settings&view='.$entity.'&entity='.$entity.'&no_history=1&"+order,
							{opt12: 1, save: 1}
						, function(data){
							window.location = "index.php?mod=settings&view='.$entity.'";
						});
					}
				</script>';
		}

		echo '<div class="popupHeader">'.msg('reorder_header_'.$entity).'</div>'.$r.$js;
	}
}

/**
 *
 * @param $entity
 * @param $entity_id
 * @param $tab
 * @return unknown_type
 */
function gain_tab_index_get($entity, $entity_id){
	global $db;
	$sql = SQL('SELECT tab, qty, id_user, (datediff(now(), date_updated)+1) as date_diff, date_updated
	FROM gain_tab_index
	WHERE entity=%s
	AND entity_id=%d', $entity, $entity_id); //AND tab=%s
	$tab_index_number = $db->GetAssoc($sql, 'fw');
	return $tab_index_number;
}

/**
 * update entity TAB index
 * @param entity name
 * @param entity ID
 * @param tab name
 * @param number of items
 * @param last update date
 */
function gain_tab_index_set($entity, $entity_id, $tab, $qty, $updated){
	global $db;
	$sql = SQL('SELECT COUNT(*)
	FROM gain_tab_index
	WHERE entity=%s
	AND entity_id=%d
	AND tab=%s', $entity, $entity_id, $tab);
	$data_exist = $db->GetOne($sql, 'fw');

	if ($data_exist == 0) {
		//INSERT
		$param_qry = array(
			'table' => 'gain_tab_index',
			'cols' => array(
				'entity', '%s', $entity,
				'entity_id', '%d', $entity_id,
				'tab', '%s', $tab,
				'qty', '%f', $qty,
				'date_updated', '%s', $updated,
				'id_user', '', 0,
			)
		);
		$id = db_query($param_qry);
	} else {
		//UPDATE
		$param_qry = array(
			'table' => 'gain_tab_index',
			'cols' => array(
				'qty', '%f', $qty,
				'date_updated', '%s', $updated,
				'id_user', '', 0,
			),
			'where' => SQL('entity=%s AND entity_id=%d AND tab=%s', $entity, $entity_id, $tab)
		);
		db_query($param_qry);
	}
}

/**
 * TODO change to use module entities view share_link
 *
 * Enter description here ...
 */
function gain_sharelink() {
	global $db, $cache_user, $cache_department, $global_config;
	if ($cache_user) {
		foreach ($cache_user as $k => $v) {
			if ($v['user_status'] == 1 && $k != $_SESSION['gain_user_id']) {
				$email_list[$v['email']] = $v['firstname'].' '.$v['lastname'];
				$department_mail_list[$v['id_department']][$v['email']] =  $v['firstname'].' '.$v['lastname'].' ('. $v['abbr'] .')';
			}
		}

		if ($cache_department) {
			foreach ($cache_department as $id_department => $department_info) {
				if ($department_mail_list[$id_department]) {
					natcasesort($department_mail_list[$id_department]);

					if ($department_info['department_abbr']) {
						$mail_list[$department_info['department_abbr']] = $department_mail_list[$id_department];
					} else {
						$mail_list[$department_info['department_name']] = $department_mail_list[$id_department];
					}
				}
			}
		}
	}

	if ($_POST['submit']) {
		//add information to db
		$id_user = $_SESSION['gain_user_id'];
		$session_msg = print_r($_SESSION, true);
		$mailfrom = $cache_user[$id_user]['email'];
		$mailfrom_name = $cache_user[$id_user]['firstname'].' '.$cache_user[$id_user]['lastname'];

		//prepare mail
		$subject = msg('share').' '.$_POST['sharelink_name'];
		require_once('lib/class/class.phpmailer.php');

//'Name: '.$mailfrom_name.
		$msg = 'URL: '.$_POST['url_sharelink']."\n\r";
		$msg_html = 'URL: <a href="http://'.$_POST['url_sharelink'].'">'.$_POST['url_sharelink'].'</a>'."<br><br>";
		$msg_post_html = 'Message: '.nl2br(htmlspecialchars($_POST['message']));
		$mailer = new PHPMailer();
		$mailer->CharSet = 'utf-8';
		if ($mailfrom) {
			$mailer->From = $mailfrom;
			$mailer->FromName = $mailfrom_name;
			$mailer->Sender = $mailfrom;
		}
		$mailer->AddAddress($_REQUEST['who_email']);
		$mailer->Subject = $subject;
		$mailer->Body = $msg_html.$msg_post_html;
		$mailer->AltBody = $msg.'Message: '.$_POST['message'];
		if ($mailer->Send()) {
			$data['complete'] = 1;
			$data['message'] = msg('link_has_been_shared');
		} else {
			$data['complete'] = 0;
			$data['error'] = msg('problem with sending email');
		}

		return json_encode($data);
	} else {
	$url = gain_entity_get_entity_detail($_REQUEST['item'], 'detail_link');
	if (!is_array($url)) {
		$url = trim($url, "index.php");
	}
	$r = '<div class="popupHeader">'.msg('share').'</div>
				<div id="sharelink_formshow">
					<form id="ajax_form_sharelink" action="index.php?fajax=1&mod=sharelink" method="post">

					<table>
						<tr>
							<td colspan =2><strong>'.clean($_REQUEST['displayname']).'</strong></td>
						</tr>
						<tr>
							<td colspan =2><input type="text" style="width: 370px;" maxlength="100" name="url_sharelink"></td>
						</tr>
						<tr>
							<td class="fw-form_head">' . msg('who') . ': </td>
							<td>'.form_select_group('who_email', array('values' => array('label' => $mail_list), 'default' => '', 'param1' => 200)).'</td>
						</tr>
						<tr>
							<td style="vertical-align: top">'.msg('sharelink_message').': </td>
							<td><textarea style="width: 300px; height: 120px;" name="message"></textarea></td>
						</tr>
						<tr>
							<td colspan="2" style="text-align: right">
								<input type="hidden" name="sharelink_name" />
								<input type="hidden" name="request_url" />
								<input type="submit" name="submit" class="btn medium green awesome btn-add" value="'.msg('share').'" />
							</td>
						</tr>
					</table>
				</form>
		</div>
		<script type="text/javascript">
			$(document).ready(function(){
				var request_url = $("#support_app_url").text();
				var url = "'.$url.'";
				url = url.replace(/&amp;/g,"&");
				if ("'.$_REQUEST['item'].'" == "clients_people") {
					$("#ajax_form_sharelink input[name=url_sharelink]").val("'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'"+url+"'.$_REQUEST['item_id'].'");
				} else {
					$("#ajax_form_sharelink input[name=url_sharelink]").val("'.$_SERVER['HTTP_HOST'].'"+request_url);
				}
				$("#ajax_form_sharelink input[name=sharelink_name]").val("'.clean($_REQUEST['displayname']).'");
				$("#ajax_form_sharelink").ajaxForm({
				    dataType: "json",
					success: sharelink_submitted
				});
			});
			function sharelink_submitted (jsonData) {
				if (jsonData.complete == 1) {
					closePopup($("#ajax_form_sharelink"));
					$("#entity_tool_box_popup").hide();
					alert(jsonData.message);
				} else {
					alert("not complete");
				}
			}
		</script>
		';
	return $r;

	}
}

/**
 *
 * set submenu for listing page
 * @param $entity
 * @param $tabs
 * @param $optional
 */
function gain_entity_set_items_submenu($basics, $tabs, $optional = array()){
	global $tpl;
	$entity = $basics['entity'];
	if ($tabs) {
		$set_sub = array();
		$option = array('add');
		if ($basics['submenu_set'] == -1) {
			unset($option[0]);
		}
		foreach ($option as $k2 => $v2) {
			foreach ($tabs as $k => $v) {
				$linked = 'index.php?mod='.$v['entity'].'&link=add';
				$class = '';
				if (check_permission('add', trim($k)) == 1) {
					$set_sub[$v2][$v['entity']] = '<a href="'.$linked.'"'.$class.' class="submenu_'.$k.'_'.$v2.'">&raquo; '.msg('add '.$v['entity']).'</a>';
				}
			}
		}
		if ($set_sub) {
			foreach ($set_sub as $k => $v) {
				if ($v) {
//					gain_set_submenu('<img src="im/'.$k.'.png" title="'.$k.'"/> ');
					foreach ($v as $k2 => $v2) {
						gain_set_submenu($v2);
					}
				}
			}
		}
//		if ($basics['manage_group_set'] != -1) {
//			gain_set_submenu('<a href="#manage_group" onclick="fw_manage_entity_group_user(this, \''.$entity.'\', \''.$_REQUEST['mod'].'\');"> &raquo; '.msg('manage_group').'</a>');
//		}
	}

	if ($optional) {
		foreach ($optional as $k => $v) {
			gain_set_submenu($v);
		}
	}
}

/**
 * show submenu when show detail/form
 * Enter description here ...
 * @param unknown_type $entity
 */
function gain_entity_set_items_submenu_view_zone($entity, $optional = array()){
	global $cm_menu;
	if (isset($cm_menu['M'][$entity]['M'])) {
		$main = $cm_menu['M'][$entity]['M'];
		foreach ($cm_menu['M'][$main]['E'] as $k => $v) {
			if (check_permission('add', trim($v)) == 1) {
				$linked = 'index.php?mod='.$v.'&link=add';
				$add_submenu[] = '<a href="'.$linked.'">&raquo; '.msg('add '.$v).'</a>';
			}
		}
	} else {
		$linked = 'index.php?mod='.$entity.'&link=add';
		$add_submenu[] = '<a href="'.$linked.'">&raquo; '.msg('add '.$entity).'</a>';
	}

	if ($add_submenu){
//		gain_set_submenu('<img src="im/add.png" title="add"/> ');
		foreach ($add_submenu as $k => $v) {
			gain_set_submenu($v);
		}
	}
	if ($optional) {
		foreach ($optional as $k => $v) {
			gain_set_submenu($v);
		}
	}
}

/**
 *
 * manage group: reorder, change name, set share, active
 * /
 */
function gain_entities_manage_entity_group_user() {
	global $db, $cache_user, $cm_menu;
	$search_token = $_REQUEST['search_token'];
	$entity = $_REQUEST['entity'];
	$mod = $_REQUEST['module'];
	$id_user = $_SESSION[SESSION_L];

	if ($cm_menu['M'][$mod]['E']) {
		foreach ($cm_menu['M'][$mod]['E'] as $key => $ent) {
			//get group from table group
			$tabs_x = gain_entity_set_group($ent);
			foreach ($tabs_x as $k2 => $v2) {
				$tabs[$k2] = $v2;
			}
		}
	} else {
		$tabs = gain_entity_set_group($entity);
	}

	if ($_REQUEST['group']) {
		if ($cm_menu['M'][$mod]['E']) {
			foreach ($cm_menu['M'][$mod]['E'] as $key => $ent) {
				$sql = SQL('DELETE FROM gain_fw_entity_group_user
				WHERE id_user=%d
				AND entity=%s', $id_user, $ent);
				$db->Execute($sql);
			}
		} else {
			$sql = SQL('DELETE FROM gain_fw_entity_group_user
			WHERE id_user=%d
			AND entity=%s', $id_user, $entity);
			$db->Execute($sql);
		}
		$tabs_tmp = $tabs;
		foreach ($_REQUEST['group'] as $k => $v) {
			$group_active_set = 0;
			if ($_REQUEST['group_active'] && in_array($v, $_REQUEST['group_active'])) {
				$group_active_set = 1;
			}
			$param_sql = array(
				'table' => 'gain_fw_entity_group_user',
				'cols' => array(
					'group_token', '%s', $v,
					'entity', '%s', $tabs_tmp[$v]['entity'],
					'id_user', '%d', $id_user,
					'group_order', '%s', $k,
					'group_active', '%s', $group_active_set,
				),
			);
			db_query($param_sql);

			//update group name
			if ($_REQUEST['group_name'][$v]) {
				$param_sql = array(
					'table' => 'gain_fw_entity_group',
					'cols' => array(
						'group_name', '%s', $_REQUEST['group_name'][$v],
						'manage_access', '%s', 'my self',
						'manage_permission', '%s', 'full',
					),
					'where' => SQL('group_token=%s', $v),
				);
				db_query($param_sql);
			}
			unset($tabs[$v]);
		}

		$param_sql = array(
			'table' => 'gain_fw_entity_group',
			'cols' => array(
				'share', '%s', '0',
				'updated', '', 'NOW()',
				'updated_by', '%f', $_SESSION[SESSION_L],
			),
			'where' => SQL('added_by=%d', $_SESSION[SESSION_L]),
		);
		db_query($param_sql);

		if ($_REQUEST['group_share']) {
			foreach ($_REQUEST['group_share'] as $k => $v) {
				$group_name = $_REQUEST['group_name'][$v];
				$manage_access = $_REQUEST['manage_access'][$v];
				$manage_permission = $_REQUEST['manage_permission'][$v];
				$param_sql = array(
					'table' => 'gain_fw_entity_group',
					'cols' => array(
						'share', '%s', '1',
						'manage_access', '%s', $manage_access,
						'manage_permission', '%s', $manage_permission,
					),
					'where' => SQL('group_token=%s', $v),
				);
				db_query($param_sql);
				
				if ($_REQUEST['notify_mail'][$v]) {
					//send mail here
					foreach ($_REQUEST['notify_mail'][$v] as $entityx => $vk) {
						gain_entities_manage_entity_group_notify_mail($group_name, $manage_access, $manage_permission, $entityx);
					}
				}
			}
		}

		//remove group
		if ($tabs) {
			foreach ($tabs as $k => $v) {
				//remove group
				$param_sql = array(
					'table' => 'gain_fw_entity_group',
					'cols' => array(
						'updated', '', 'NOW()',
						'updated_by', '%f', $_SESSION[SESSION_L],
						'removed', '', 'NOW()',
						'removed_by', '%d', $_SESSION[SESSION_L],
					),
					'where' => SQL('group_token=%s AND permanent_group!=1', $k),
				);
				db_query($param_sql);
			}

			$sql = SQL('DELETE FROM gain_fw_entity_group_item
			WHERE group_token=%s', $k);
			$db->Execute($sql);

			$sql = SQL('DELETE FROM gain_fw_entity_group_user
			WHERE group_token=%s', $k, $_SESSION[SESSION_L]);
			$db->Execute($sql);
		}
		exit;
	}
	if ($tabs) {
		foreach ($tabs as $k => $v) {
			if ($v['main'] == 0 && ($v['id_user'] == $_SESSION[SESSION_L] || $v['share'] == 1) && $v['permanent_group'] != 1) {
				$group_active_default = '';
				$group_share_default = '';

				$v_active = 2;
				if ($v['group_active'] == 1) {
					$group_active_default = ' checked';
					$v_active = 0;
				}

				if ($v['share'] == 1) {
					$group_share_default = ' checked';
				}

				if ($v['id_user'] == $_SESSION[SESSION_L] && $v_active != 0) {
					$v_active = 1;
				}

				$displayonly = 0;
				$group_append = '';
				$group_share = '';
				$notify_mail = '';
				
				$manage_access_list = array('department' => msg('my department'), 'all' => msg('everyone'));
				$manage_permission_list = array('view_only' => msg('view only'), 'full' => msg('full permission'));
						
				if ($v['id_user'] != $_SESSION[SESSION_L]) {
					$in_active = 0;
					if ($v['manage_access'] == 'department') {
						if ($_SESSION[SESSION_A]['department'] != $cache_user[$v['id_user']]['id_department']) {
							$in_active = 1;
						}
					}
					$group_append = ' ['.count($v['group_id_arr']).'] ('.$cache_user[$v['id_user']]['abbr'].')';
					$displayonly = 1;

					$manage_access = '<div style="display: inline; position: absolute; left: 330px;">' . $manage_access_list[$v['manage_access']] . '</div>';
					$manage_permission = '<div style="display: inline; position: absolute; left: 560px;">' . $manage_permission_list[$v['manage_permission']] . '</div>';
				} else {
					$group_share = '<p class="input_align_h" style="position: absolute; left: 265px;">
						<input type="checkbox" value="'.$v['entity_key'].'"'.$group_share_default.' name="group_share[]" class="brd0" id="check-group_share-'.$v['entity_key'].'">
						<label for="check-group_share-'.$v['entity_key'].'">&nbsp;</label>
					</p>';

					$manage_readonly = 'block';
					$manage_readonly2 = 'none';
					if ($v['share'] != 1) {
						$manage_access_default = 'department';
						$manage_permission_default = 'view_only';

						$manage_readonly = 'none';
						$manage_readonly2 = 'block';
						$notify_show = ' hide';
					} else {
						$manage_access_default = $v['manage_access'];
						$manage_permission_default = $v['manage_permission'];
						$notify_show = '';
						
					}
					$notify_mail_default = '<p class="input_align_v'.$notify_show.'"><input id="notify_mail_'.$v['entity_key'].'" type="checkbox" name="notify_mail['.$v['entity_key'].']['.$v['entity'].']" value="notify_mail"><label for="notify_mail_'.$v['entity_key'].'"> '.msg('send mail').'</label></p>';

					$manage_access_form = '
						<span style="display: '.$manage_readonly.';">' . form_radio('manage_access['.$k.']', array('values' => $manage_access_list, 'default' => $manage_access_default, 'displayonly' => $manage_readonly)) . '</span>
						<span style="display: '.$manage_readonly2.';">' . msg('my self').'</span>';
					$manage_permission_form = '
						<span style="display: '.$manage_readonly.';">' . form_radio('manage_permission['.$k.']', array('values' => $manage_permission_list, 'default' => $manage_permission_default, 'displayonly' => $manage_readonly)) . '</span>
						<span style="display: '.$manage_readonly2.';">' . msg('full permission') . '</span>';
					
					$manage_access = '<div id="manage_access_'.$v['entity_key'].'" style="display: inline; position: absolute; left: 330px;">' . $manage_access_form . '</div>';
					$manage_permission = '<div id="manage_permission_'.$v['entity_key'].'" style="display: inline; position: absolute; left: 560px;">' . $manage_permission_form . '</div>';
					$notify_mail = '<div id="manage_notify_'.$v['entity_key'].'" style="display: inline; position: absolute; left: 780px;">' . $notify_mail_default . '</div>';
				}

				if ($in_active == 0) {
					$group_remove = '';
					//check permission later : need alert msg for sure or set to gray color and no
					if ($_SESSION[SESSION_P]['permissions']['menu']['global']['manage_group'] == 1 || $_SESSION[SESSION_L] == $v['id_user']) {
						$action_delete = 'remove_group';
						if ($_SESSION[SESSION_L] != $v['id_user']) {
							$action_delete = 'remove_group_other';
						}
						$group_remove = ' <img src="im/remove.png" class="fw-point" title="'.msg('delete').'" onclick="fw_manage_entity_group(this,\''.$v['entity'].'\', \''.$v['entity_key'].'\', \''.addslashes($v['entity_tabs_name']).'\', \''.$action_delete.'\', \'\', \'\', 0)" style="position: absolute; left: 870px;"/>';
					}
					//$group_listk[$v['entity']][$v_active][$v['entity_tabs_name']] = '<li>'.$v_active.'|'.$v['entity'].' - '.$v['entity_tabs_name'].'</li>';
					$tmp = '<li id="group_'.$v['entity_key'].'">
						<img src="im/sort.png" class="move_me" style="cursor: move; float: left;" />
						<p class="input_align_h">
							<input type="checkbox" value="'.$v['entity_key'].'"'.$group_active_default.' name="group_active[]" class="brd0" id="check-group_active-'.$v['entity_key'].'">
							<label for="check-group_active-'.$v['entity_key'].'">&nbsp;</label>
						</p>
						<div class="input_align_h">';

					if ($displayonly == 1) {
						$tmp .= '<label for="check-group_active-'.$v['entity_key'].'">';
						
					}
	
					$tmp .= form_input('group_name['.$v['entity_key'].']', array('default' => htmlspecialchars_decode($v['entity_tabs_name']), 'displayonly' => $displayonly, 'append' => $group_append, 'param1' => '170', 'param2' => 30));
					if ($displayonly != 1) {
						$tmp .= '</label>';
					}
				
					$tmp .= '
						</div>' . $group_share . $manage_access . $manage_permission . $notify_mail . $group_remove . '<br class="clr"/>
					</li>';
					$group_list[$v['entity']][$v_active][strtolower($v['entity_tabs_name']).$v['entity_key']] = $tmp;
				}
			}
		}
	}

	$r = '<div class="popupHeader">'.msg('manage_group').'</div>
		<div class="detailsInfo">';
	if ($group_list) {
		$r .= '<form id="fw_group_order_form">
		<script type="text/javascript">
			var confirm_remove_group_other = "'.msg('confirm_remove_group_other').'";
			var confirm_remove_group = "'.msg('confirm_remove_group').'";
			var permanently = "'.msg('permanently').'";
		</script>
			<table width="100%" cellspacing="1" cellpadding="4">';
		foreach ($group_list as $k => $v) {
			$v0 = $v1 = $v2 = '';
			$cnt = 0;
			if ($v[0]) {
				$v0 = implode('', $v[0]);
				$cnt += count($v[0]);
			}
			if ($v[1]) {
				$v1 = '';
				$after_sort = array_keys($v[1]);
				natcasesort($after_sort);
				if ($after_sort) {
					foreach ($after_sort as $k3 => $v3) {
						$v1 .= $v[1][$v3];
					}
				}
				$cnt += count($v[1]);
			}
			if ($v[2]) {
				$v2 = '';
				$after_sort = array_keys($v[2]);
				natcasesort($after_sort);
				if ($after_sort) {
					foreach ($after_sort as $k3 => $v3) {
						$v2 .= $v[2][$v3];
					}
				}
				$cnt += count($v[2]);
			}

			$r .= '
				<tr><td>
					<strong>'.msg('menu_'.$k).'</string>
					<strong style="position: absolute; left: 265px;">'.msg('fw_group_share').'</strong>
					<strong style="position: absolute; left: 330px;">'.msg('who can access').'</strong>
					<strong style="position: absolute; left: 560px;">'.msg('permission').'</strong>
					<strong style="position: absolute; left: 780px;">'.msg('notification').'</strong>
				</td></tr>
				<tr><td>
					<ul id="fw_group_order_'.$k.'"'.$style.'>
					'.$v0.$v1.$v2.'
					</ul>
				</td></tr>
				<script type="text/javascript">
					$("#fw_group_order_'.$k.'").sortable({handle: $("img.move_me")});
					gain_ul_effect("fw_group_order_'.$k.'");
				</script>
				';
		}
		$r .= '	<tr>
				<td>
					<input style="float: right;" class="btn medium gray awesome btn-cancel" type="button" value="'.msg('cancel').'" onClick="$(\'#tab_menu_search_result\').tabs(\'select\', 1);"/> <input style="float: right; margin-right: 5px;" class="btn medium green awesome btn-add" type="button" value="'.msg('opt2').'" onClick="fw_manage_entity_group_user_save(\''.$entity.'\', \''.$mod.'\');"/>
				</td>
				</tr>
				</table>
				</form>';
	} else {
		$r .= fw_notify_msg('need to create group');
	}

	$r .= '</div>
	<script type="text/javascript">
		var module_refresh = "'.$_REQUEST['module'].'";

		$(document).ready(function(){
			$("input[id^=check-group_share-]").click(function(){
				var manage_access = $(this).parents("li").attr("id").replace("group_", "manage_access_");
				$("#"+manage_access).find("span").each(function(){
					if ($(this).css("display") == "block") {
						$(this).css("display", "none");
					} else {
						$(this).css("display", "block");
					}
				});
				
				var manage_permission = $(this).parents("li").attr("id").replace("group_", "manage_permission_");
				$("#"+manage_permission).find("span").each(function(){
					if ($(this).css("display") == "block") {
						$(this).css("display", "none");
					} else {
						$(this).css("display", "block");
					}
				});
				
				var manage_notify = $(this).parents("li").attr("id").replace("group_", "manage_notify_");
				$("#"+manage_notify).find("p").each(function(){
					if ($(this).css("display") == "block") {
						$(this).css("display", "none");
						$(this).find("input").attr("checked", false);
					} else {
						$(this).css("display", "block");
					}
				});
			});
		});
	</script>
	';
	return $r;
}

function gain_entities_manage_entity_group_notify_mail($group_name, $manage_access, $manage_permission, $entity, $type = ''){
	global $cache_user, $global_config;

	$manage_permission_list = array('view_only' => msg('view only per'), 'full' => msg('full per'));

	$mail_content = $global_config['system']['manage_email_content_other'];
	if ($type == '') {
		$type = 'published by';
		$mail_content = $global_config['system']['manage_email_content'];
	}
	$mail_subject = $global_config['system']['manage_email_subject'];
	$mail_subject = str_replace('{group_name}', $group_name, $mail_subject);
	$mail_subject = str_replace('{action}', msg($type), $mail_subject);
	$mail_subject = str_replace('{user}', $_SESSION[SESSION_N], $mail_subject);

//	$mail_content = $global_config['system']['manage_email_content'];
	$mail_content = str_replace('{user}', $_SESSION[SESSION_N], $mail_content);
	$mail_content = str_replace('{type}', msg($type), $mail_content);
	$mail_content = str_replace('{group_name}', $group_name, $mail_content);
	$mail_content = str_replace('{entity}', msg($entity), $mail_content);
	$mail_content = str_replace('{permission}', $manage_permission_list[$manage_permission], $mail_content);
	$mail_content .= '<br/><br/>' . $global_config['system']['mail_footer'];

	$from = $global_config['system']['support_email'];
	$name = 'gain+CRM';
	if ($cache_user) {
		foreach ($cache_user as $k => $v) {
			if ($v['user_status'] == 1) {
				if (($manage_access == 'department' && $v['id_department'] == $_SESSION[SESSION_A]['department']) || $manage_access == 'all') {
					$to = $v['email'];
					$to = 'shella@nsasia.co.th';
					//$to = 'orawan@nsasia.co.th';
					if ($to != '') {
						//$mail_subject_add = '|' . $k . '|' . $v['firstname'];
						gain_send_mail($from, '', '', $name, $to, $mail_subject . $mail_subject_add, $mail_content);
					}
				}
			}
		}
	}
}

/**
 *
 * add new group, update item group
 */
function gain_entities_manage_entity_group(){
	global $db, $cache_user, $global_config;
	$entity = $_REQUEST['entity'];
	$tabs = gain_entity_set_group($_REQUEST['entity']);

	$manage_access_list = array('department' => msg('my department'), 'all' => msg('everyone'));
	$manage_permission_list = array('view_only' => msg('view only'), 'full' => msg('full permission'));
	
	if ($_REQUEST['gaction'] == 'remove_group') {
		$group_token = $_REQUEST['group_token'];
		//keep where conditions
		$sql = SQL('SELECT where_condition, group_url, group_name, manage_access, manage_permission, share
		FROM gain_fw_entity_group
		WHERE group_token=%s', $group_token);
		$group_info = $db->GetRow($sql);

		//remove group
		$param_sql = array(
			'table' => 'gain_fw_entity_group',
			'cols' => array(
				'updated', '', 'NOW()',
				'updated_by', '%d', $_SESSION[SESSION_L],
				'removed', '', 'NOW()',
				'removed_by', '%d', $_SESSION[SESSION_L],
			),
			'where' => SQL('group_token=%s', $_REQUEST['group_token']),
		);
		db_query($param_sql);

		$sql = SQL('DELETE FROM gain_fw_entity_group_user WHERE group_token=%s', $_REQUEST['group_token']);
		$db->Execute($sql);

		$sql = SQL('DELETE FROM gain_fw_entity_group_item WHERE group_token=%s', $_REQUEST['group_token']);
		$db->Execute($sql);
		
		if ($group_info['share'] == 1) {
			//notify mail
			//gain_entities_manage_entity_group_notify_mail($group_info['group_name'], $group_info['manage_access'], $group_info['manage_permission'], $entity, 'deleted');
		}

		exit;
	} else if ($_REQUEST['gaction'] == 'active_group') {
		//update active group
		$param_sql = array(
			'table' => 'gain_fw_entity_group_user',
			'cols' => array(
				'group_active', '%s', '0',
			),
			'where' => SQL('id_user=%d AND group_token=%s', $_SESSION[SESSION_L], $_REQUEST['group_token']),
		);
		db_query($param_sql);

		$module = gain_entity_get_entity_detail($_REQUEST['entity']);
		if ($module['mod_main'] != '') {
			echo $module['mod_main'];
		} else {
			echo $_REQUEST['entity'];
		}
		exit;
	} else if ($_POST['submit'] || $_REQUEST['filter_as_group'] == 2) {
		//get all id
		if ($_POST['action_group'] == 'remove_from') {
			$item_selected = gain_entities_get_search_id($_POST['item_selected'], $_POST['entity_token']);
			$sql = SQL('DELETE FROM gain_fw_entity_group_item
			WHERE group_id IN('.$item_selected.')
			AND group_token=%s', $_POST['group_token']);
			$db->Execute($sql);
			
			gain_entities_manage_entity_group_update($_REQUEST['group_token']);
			//notify mail
			if ($_POST['remove_and_notify']) {
				//keep where conditions
				$sql = SQL('SELECT where_condition, group_url, group_name, manage_access, manage_permission, share, added_by
				FROM gain_fw_entity_group
				WHERE group_token=%s', $_REQUEST['group_token']);
				$group_info = $db->GetRow($sql);
				//gain_entities_manage_entity_group_notify_mail($group_info['group_name'], $group_info['manage_access'], $group_info['manage_permission'], $entity, 'fw_updated');
			}
			echo $_REQUEST['group_token'];
		} else if ($_POST['action_group'] == 'create_group') {
			$item_selected = gain_entities_get_search_id($_POST['item_selected'], $_POST['entity_token'], 1);
			$group_name = $_POST['group_name'];
			$manage_access = $_REQUEST['manage_access'];
			$manage_permission = $_REQUEST['manage_permission'];
			if ($_POST['create_new_options']) {
				if (in_array('share_group', $_POST['create_new_options'])) {
					$share_set = 1;
					if ($_POST['notify_mail']) {
						gain_entities_manage_entity_group_notify_mail($group_name, $manage_access, $manage_permission, $entity);
					}
				}
			}

			//add new group INSERT
			$gtoken = 't'.md5(time().'_'.$entity.'_'.$_SESSION[SESSION_L]);

			$param_sql = array(
				'table' => 'gain_fw_entity_group',
				'cols' => array(
					'group_token', '%s', $gtoken,
					'entity', '%s', $entity,
					'group_name', '%s', $group_name,
					'share', '%s', $share_set,
					'manage_access', '%s', $manage_access,
					'manage_permission', '%s', $manage_permission,
					'added', '', 'NOW()',
					'added_by', '%d', $_SESSION[SESSION_L],
					'updated', '', 'NOW()',
					'updated_by', '%f', $_SESSION[SESSION_L],
				),
			);

			if ($_REQUEST['filter_as_group'] == 1) {
				//get entity_token and group token
				//$entity_token = $_REQUEST['entity_token'];

				$group_token = $_REQUEST['group_token'];

				$sql = SQL('SELECT search_token, search_link, search_num
				FROM gain_fw_search_history
				WHERE search_entities=%s
				AND search_by=%d
				ORDER BY search_date DESC', $group_token, $_SESSION[SESSION_L]);
				$search_info = $db->GetRow($sql);

				//get qry and link for entity_token

				$sql = SQL('SELECT where_condition, group_url
				FROM gain_fw_entity_group
				WHERE group_token=%s', $group_token);
				$group_info = $db->GetRow($sql);

				if (trim($group_info['where_condition']) != '') {
					$param_sql['cols'][] = 'where_condition';
					$param_sql['cols'][] = '%s';
					$param_sql['cols'][] = ' '.$group_info['where_condition'];
				}
				if ($search_info['search_link']) {
					$a = explode('&entity=' . $group_token, $search_info['search_link']);
					$group_url = 'index.php?mod=' . $entity . '&search_for=' . $gtoken . '&entity=' . $gtoken . str_replace('&' . $group_token, '&' . $gtoken, $a[1]);
				}
				//add condition fields
				$param_sql['cols'][] = 'num';
				$param_sql['cols'][] = '%d';
				$param_sql['cols'][] = $search_info['search_num'];

				if ($b[$group_token] || $group_url) {
					//add condition fields
					$param_sql['cols'][] = 'group_url';
					$param_sql['cols'][] = '%s';
					$param_sql['cols'][] = $group_url;
				}
			}
			db_query($param_sql);

			//add to group order list
			//get group_order
			$sql = SQL('SELECT group_order
			FROM gain_fw_entity_group_user
			WHERE id_user=%d
			AND group_active=1
			AND entity=%s
			ORDER BY group_order DESC', $_SESSION[SESSION_L], $entity);
			$group_order = ($db->GetOne($sql)+1);
			$param_sql = array(
				'table' => 'gain_fw_entity_group_user',
				'cols' => array(
					'group_token', '%s', $gtoken,
					'entity', '%s', $entity,
					'id_user', '%d', $_SESSION[SESSION_L],
					'group_order', '%s', $group_order,
					'group_active', '%s', "1",
				),
			);
			db_query($param_sql);

			//add id
			if ($item_selected && $gtoken) {
				if ($_POST['create_new_options']) {
					if (in_array('remove_from_group', $_POST['create_new_options'])) {
						$sql = SQL('DELETE FROM gain_fw_entity_group_item
						WHERE group_id IN(' . implode(',', $item_selected) . ')
						AND group_token=%s', $_POST['group_token']);
						$db->Execute($sql);

						gain_entities_manage_entity_group_update($_POST['group_token']);
						if ($_POST['remove_and_notify']) {
							//keep where conditions
							$sql = SQL('SELECT where_condition, group_url, group_name, manage_access, manage_permission, share, added_by
							FROM gain_fw_entity_group
							WHERE group_token=%s', $_POST['group_token']);
							$group_info = $db->GetRow($sql);
							gain_entities_manage_entity_group_notify_mail($group_info['group_name'], $group_info['manage_access'], $group_info['manage_permission'], $entity, 'fw_updated');
						}
					}
				}

				foreach ($item_selected as $k => $v) {
					$param_sql = array(
						'table' => 'gain_fw_entity_group_item',
						'cols' => array(
							'group_token', '%s', $gtoken,
							'group_id', '%d', $v,
						),
					);
					db_query($param_sql);
				}
			}
			$sql = 'INSERT INTO gain_fw_search_result
			SELECT "'.$entity.'", "'.$gtoken.'", '.$_SESSION[SESSION_L].', field_name, header, field_width, sort_field, advanced_options 
			FROM gain_fw_search_result 
			WHERE entity="'.$entity.'" 
			AND entity_key="'.$_POST['group_token'].'" 
			AND id_user=' . $_SESSION[SESSION_L];
			$db->Execute($sql);
			if (!$_REQUEST['filter_as_group']) {
				gain_entities_manage_entity_group_update($gtoken);
			}
			echo $gtoken;//for redirect
			
		} else if ($_POST['action_group'] == 'add_to' || $_REQUEST['filter_as_group']) {
			if ($_REQUEST['filter_as_group'] == 2) {
				$group_token = $_REQUEST['group_token'];
				$param_sql = array(
					'table' => 'gain_fw_entity_group',
					'where' => SQL('group_token=%s', $group_token),
				);
				//get entity_token and group token
				//$entity_token = $_REQUEST['entity_token'];

				$sql = SQL('SELECT search_token, search_link, search_num
				FROM gain_fw_search_history
				WHERE search_entities=%s
				AND search_by=%d
				ORDER BY search_date DESC', $group_token, $_SESSION[SESSION_L]);
				$search_info = $db->GetRow($sql);
				//get qry and link for entity_token

				//keep where conditions
				$sql = SQL('SELECT where_condition, group_url, group_name, manage_access, manage_permission 
				FROM gain_fw_entity_group
				WHERE group_token=%s', $group_token);
				$group_info = $db->GetRow($sql);
				if (trim($group_info['where_condition']) != '') {
					$param_sql['cols'][] = 'where_condition';
					$param_sql['cols'][] = '%s';
					$param_sql['cols'][] = ' '.$group_info['where_condition'];
				}

				$b = $_REQUEST;
				if ($search_info['search_link']) {
					$a = explode('&entity=' . $group_token, $search_info['search_link']);
					parse_str($a[1], $parsed);
					$b = array_merge($b, $parsed);
				}

				//add condition fields
				$param_sql['cols'][] = 'num';
				$param_sql['cols'][] = '%d';
				$param_sql['cols'][] = $search_info['search_num'];
				if ($b[$group_token]) {
					$group_url = 'index.php?mod=' . $entity . '&search_for=' . $group_token . '&entity=' . $group_token;
					foreach ($b[$group_token] as $k => $v) {
						if ($v != '' && $k != 'page') {
							$group_url .= '&' . $group_token . '[' . $k . ']=' . $v;
						}
					}

					//add condition fields
					$param_sql['cols'][] = 'group_url';
					$param_sql['cols'][] = '%s';
					$param_sql['cols'][] = $group_url;
				}
				db_query($param_sql);
				$mod_main = gain_entity_get_entity_detail($entity, 'mod_main');
				if ($mod_main == '') {
					$mod_main = $entity;
				}

				//notify mail
				//gain_entities_manage_entity_group_notify_mail($group_info['group_name'], $group_info['manage_access'], $group_info['manage_permission'], $entity, 'updated');

				echo $mod_main.'&entity='.$group_token.'&re-act=1&act=8';
				exit;
			}

			$item_selected = gain_entities_get_search_id($_POST['item_selected'], $_POST['entity_token'], 1);
			if (isset($_POST[$_POST['exist_group']])) {
				$remove_from_group = 1;
				//$_POST['group_token']
				foreach ($item_selected as $k => $v) {
					$param_sql = array(
						'table' => 'gain_fw_entity_group_item',
						'cols' => array(
							'group_token', '%s', $_POST['exist_group'],
						),
						'where' => SQL('group_token=%s AND group_id=%d', $_POST['group_token'], $v),
					);
					db_query($param_sql);
				}
				//gain_entities_manage_entity_group_update($_POST['exist_group']);
				gain_entities_manage_entity_group_update($_POST['group_token']);
				if ($_POST['remove_and_notify']) {
					//keep where conditions
					$sql = SQL('SELECT where_condition, group_url, group_name, manage_access, manage_permission, share, added_by
					FROM gain_fw_entity_group
					WHERE group_token=%s', $_POST['group_token']);
					$group_info = $db->GetRow($sql);
					gain_entities_manage_entity_group_notify_mail($group_info['group_name'], $group_info['manage_access'], $group_info['manage_permission'], $entity, 'fw_updated');
				}
			} else {
				$sql = SQL('DELETE FROM gain_fw_entity_group_item
				WHERE group_token=%s', $_POST['exist_group']);
				$db->Execute($sql);

				$group_id_old = $tabs[$_POST['exist_group']]['group_id_arr'];
				if ($group_id_old) {
					$item_selected = array_merge($group_id_old, $item_selected);
				}
				//$item_selected =
				if ($item_selected) {
					foreach ($item_selected as $k => $v) {
						if ($v > 0) {
							$param_sql = array(
								'table' => 'gain_fw_entity_group_item',
								'cols' => array(
									'group_token', '%s', $_POST['exist_group'],
									'group_id', '%d', $v,
								),
							);
							db_query($param_sql);
						}
					}
				}
			}
			gain_entities_manage_entity_group_update($_POST['exist_group']);
			echo $_POST['exist_group'];
		}
		exit;
	}

	//set item_selected to hidden
	if ($_REQUEST['item_selected'][1]) {
		$item_selected_b = implode(',', $_REQUEST['item_selected'][1]);
		$cnt_item_selected = count($_REQUEST['item_selected'][1]);
	} else { //all
		$item_selected = gain_entities_get_search_id($_REQUEST['item_selected'][0].',', $_POST['entity_token'], 1);
		$cnt_item_selected = $_REQUEST['check_sum'];
	}
	$hidden .= '<input type="hidden" name="item_selected" value="'.$_REQUEST['item_selected'][0].','.$item_selected_b.'"/>';

	if ($_REQUEST['entity_token']) {
		$hidden .= '<input type="hidden" name="entity_token" value="'.$_REQUEST['entity_token'].'"/>';
	}

	if ($_REQUEST['entity']) {
		$hidden .= '<input type="hidden" name="entity" value="'.$_REQUEST['entity'].'"/>';
	}

	if ($_REQUEST['group_token']) {
		$hidden .= '<input type="hidden" name="group_token" value="'.$_REQUEST['group_token'].'"/>';
	}

	if ($_REQUEST['filter_as_group']) {
		$hidden .= '<input type="hidden" name="filter_as_group" value="'.$_REQUEST['filter_as_group'].'"/>';
	}
	
	if ($tabs[$_REQUEST['group_token']]['id_user'] != $_SESSION[SESSION_L]) {
		$abc = '
			<div style="display: none; margin-left: 20px;" class="radio-action-remove_from_notify_div">
				<strong>' . msg('notification') . '</strong>
				<p class="input_align_v">
					<input type="checkbox" id="radio-action-remove_from_notify{items}" class="brd0" name="remove_and_notify['.$_REQUEST['group_token'].']" value="1"> <label for="radio-action-remove_from_notify{items}">' . msg('send mail') . '</label>
				</p>
			</div>';
	}
	
	if ($tabs && !$_REQUEST['filter_as_group']) {
		foreach ($tabs as $k => $v) {
			//TODO 
			if ($v['main'] != 1 && $v['permanent_group'] != 1) {
				$manage_access = 0;
				if ($v['manage_access'] == 'department') {
					if ($cache_user[$v['id_user']]['id_department'] == $_SESSION[SESSION_A]['department']) {
						$manage_access = 1;
					}
				} else if ($v['manage_access'] == 'all') {
					$manage_access = 1;
				}

				if ((($v['id_user'] == $_SESSION[SESSION_L]) || ($v['manage_permission'] == 'full' && $manage_access == 1)) && !$v['group_url']) {
					$exist_group_arr[$v['entity_key']] = $v['entity_tabs_name'];
					if ($_REQUEST['entity'] != $_REQUEST['group_token'] && $tabs[$_REQUEST['group_token']]['permanent_group'] != 1 && !$tabs[$_REQUEST['group_token']]['group_url']) {
						if ($tabs[$_REQUEST['group_token']]['id_user'] == $_SESSION[SESSION_L] || $_SESSION[SESSION_P]['permissions']['menu']['global']['manage_group'] == 1) {
							$exist_group_arr[$v['entity_key']] .= ' <span id="fw_options_remove_'.$k.'" class="hide" style="margin-top: 20px;">#'.form_checkbox($k, array('values' => array(1 => msg('fw_remove_from_group').' <strong>'.$tabs[$_REQUEST['group_token']]['entity_tabs_name']))).'</strong></span>' . str_replace('{items}', $k, $abc);
						}
					}
				}
			}
		}
		unset($exist_group_arr[$_REQUEST['group_token']]);
	}
	$exist_group_arrx['create_group'] = msg('fw_create_group');

	if ($_REQUEST['entity'] != $_REQUEST['group_token'] && $tabs[$_REQUEST['group_token']]['permanent_group'] != 1 && !$_REQUEST['filter_as_group'] && !$tabs[$_REQUEST['group_token']]['group_url']) {
		if ($tabs[$_REQUEST['group_token']]['id_user'] == $_SESSION[SESSION_L] || $_SESSION[SESSION_P]['permissions']['menu']['global']['manage_group'] == 1) {
			$option_remove_from_current_group = '
			<tr><td colspan="2">
				<p class="input_align_v"><input id="radio-action-remove_from" type="radio" name="action_group" value="remove_from"> <label for="radio-action-remove_from">'.msg('fw_remove_from_group').' <strong>'.$tabs[$_REQUEST['group_token']]['entity_tabs_name'].'</strong></label>'.str_replace('{items}', $_REQUEST['group_token'], $abc).'</p>
				
			</td></tr>';
			$k = 'create_group_and_remove';
			$create_new_options['remove_from_group'] = msg('fw_remove_from_group').' <strong>'.$tabs[$_REQUEST['group_token']]['entity_tabs_name'].'</strong>' . $abc;
		}
	}
	$create_new_options['share_group'] = msg('fw_share_group');

	$display_create_div = ' class="hide"';
	$default_create = '';
	if (!$_REQUEST['filter_as_group'] && $exist_group_arr) {
		$head_group = '
		<tr><td>'.$header.'</td></tr>
		<tr><td><p class="input_align_v"><input id="radio-action-add_to" type="radio" name="action_group" value="add_to" checked> <label for="radio-action-add_to">'.msg('fw_add_to_group').'</label></p></td></tr>';
	} else {
		$display_create_div = '';
		$default_create = 'create_group';
	}
	$exist_group = form_radio('action_group', array('values' => $exist_group_arrx, 'align' => 'v', 'default' => $default_create, 'force_radio' => 1));
	$create_group = '<tr><td>' . $exist_group . '<div id="fw_option_create_group"' . $display_create_div . ' style="margin-left: 20px;">' . form_input('group_name', array('addon_field' => ' title="group name" id="group_name_effect"', 'param1' => 170, 'param2' => 30)) . form_checkbox('create_new_options', array('values' => $create_new_options)) . '
			<div id="share_option" class="hide">
			<strong>' . msg('who can access') . '</strong><br class="clr"/>' . form_radio('manage_access', array('values' => $manage_access_list, 'default' => 'department')) . '<br class="clr"/><br/>
			<strong>' . msg('permission') . '</strong><br class="clr"/>' . form_radio('manage_permission', array('values' => $manage_permission_list, 'default' => 'view_only')) . '<br class="clr"/><br/>
			<strong>' . msg('notification') . '</strong><br class="clr"/><p class="input_align_v"><input id="notify_mail" type="checkbox" name="notify_mail" value="notify_mail"> <label for="notify_mail"> '.msg('send mail').'</label></p>
			</div>
		</div></td></tr>';

	$exist_group = form_radio('exist_group', array('values' => $exist_group_arr, 'align' => 'v', 'default' => $default_create, 'force_radio' => 1));

	$header = msg('group_header_quetion');
	$header = str_replace('item_selected', $cnt_item_selected, $header);
	
	if ($_REQUEST['entity'] != $_REQUEST['group_token'] && $tabs[$_REQUEST['group_token']]['id_user'] != $_SESSION[SESSION_L] && $_SESSION[SESSION_P]['permissions']['menu']['global']['manage_group'] == 1){
		$notify_msg = '<div style="margin-top: 5px;">'.fw_notify_msg('warning_manage_group').'</div>';
	}

	//set refresh page
	$module_info = gain_entity_get_entity_detail($_REQUEST['entity']);
	$entity_refresh = $_REQUEST['entity'];
	if ($module_info['mod_main'] != '') {
		$entity_refresh = $module_info['mod_main'];
	}

	echo '<div class="popupHeader">'.msg('fw_manage_group').'</div>
		<div class="detailsInfo">
		'.$notify_msg.'
			<form id="fw_manage_group" action="index.php?ajax=1&mod=entities&view=manage_entity_group" method="post">'.$hidden.'
			<table cellspacing="1" cellpadding="4" width="100%">
				' . $head_group . '
				<tr id="content_radio_add_to"><td style="padding-left: 30px;">' . $exist_group . '</td></tr>
				' . $create_group 
				. $option_remove_from_current_group . '
				<tr><td colspan="2" align="right"><input type="submit" class="btn medium green awesome btn-add" name="submit" value="submit"/></td></tr>
			</table>
			</form>
		</div>
		<script type="text/javascript">
			$(document).ready(function(){
				if ("'.$_REQUEST['filter_as_group'].'" != 1) {
					$("input[id^=check-]").parent().hide().find("input[type=checkbox]").attr("checked", false);
				}
				
				$("input[id^=check-]").click(function(){
					$("div.radio-action-remove_from_notify_div").hide().find("input[type=checkbox]").attr("checked", false);
					if ($(this).attr("checked")) {
						$(this).parent().next("div").show();
					}
				});
				
				$("#check-create_new_options-share_group").click(function(){
					if ($(this).attr("checked") == true || $(this).attr("checked") == "checked") {
						$("#share_option").show();
					} else {
						$("#share_option").hide();
					}
				});
			});

			var notify_group_new = "'.msg('notify_group_new').'";
			var notify_group_update = "'.msg('notify_group_update').'";
			$("#group_name_effect").hint();
			$("#radio-action-remove_from").click(function(){
				$("#content_radio_add_to").hide();
				$fw_create_group = $("#fw_option_create_group");
				$("#fw_option_create_group").hide();

				//clear form
				$("input[id^=radio-exist_group-]").attr("checked", false);
				$fw_create_group.find("input[name=group_name]").val("");
				$fw_create_group.find("input[type=checkbox]").attr("checked", false);
				$("div.radio-action-remove_from_notify_div").hide().find("input[type=checkbox]").attr("checked", false);
				$(this).parent().next("div").show();
			});

			if ($("input[id^=radio-action][checked]").val() == "create_group") {
				$("#check-create_new_options-remove_from_group, #check-create_new_options-share_group").parent().show();
				$("#fw_option_create_group").show();
			}
			$("input[id^=radio-action]").click(function(){
				var value_exist_option = $(this).val();
				$("#check-create_new_options-remove_from_group, #check-create_new_options-share_group").parent().hide();
				$("#fw_option_create_group").hide();
				$("#content_radio_add_to").hide();
				if (value_exist_option == "create_group") {
					$("#fw_option_create_group").show();
					$("#check-create_new_options-remove_from_group, #check-create_new_options-share_group").parent().show();
				} else {
					$("#content_radio_add_to").show();
					$("div.radio-action-remove_from_notify_div").hide().find("input[type=checkbox]").attr("checked", false);
					$(this).parent().next("div").show();
				}
			});
			
			$("input[id^=radio-exist_group-]").click(function(){
				$("#radio-action-add_to").attr("checked", true);
				$("div.radio-action-remove_from_notify_div").hide().find("input[type=checkbox]").attr("checked", false);
				var id_exist_option = $(this).attr("id");
				var value_exist_option = $(this).val();
				
				$("input[id^=check-]").parent().hide().find("input[type=checkbox]").attr("checked", false);

				$("#fw_option_create_group").hide();
				$("span[id^=fw_options_remove_]").hide();

				$("input[id^=check-"+value_exist_option+"]").parent().css("margin-left", "20px").show();
			});

			$("#fw_manage_group").ajaxForm({
				beforeSubmit: showRequest,
				success: function(data) {
					param = "&search_for=" + data + "&entity=" + data + "&re-act=1";
					if ($("input[name=exist_group]:checked").val() == "create_group") {
						window.location = "index.php?mod='.$entity_refresh.'&act=6";
					} else {
						param = param + "&act=7";
						window.location = "index.php?mod='.$entity_refresh.'"+param;
					}
				}
			});

			function showRequest(formData, jqForm, options) {
				$("#fw_manage_group").find("input.awesome").hide().parent().append("<span style=\"line-height: 21px; float: right;\">Loading...</span>");
			}
	</script>
		';
}

function gain_entities_manage_entity_group_update($group_token) {
	global $db;
	$sql = SQL('SELECT COUNT(group_id)
	FROM gain_fw_entity_group_item
	WHERE group_token=%s', $group_token);
	$num = $db->GetOne($sql);
	$param_sql = array(
		'table' => 'gain_fw_entity_group',
		'cols' => array(
			'num', '%s', $num,
		),
		'where' => SQL('group_token=%s', $group_token),
	);
	db_query($param_sql);
}

function gain_entities_add_mailing(){
	global $db, $cache_user;

	if ($_REQUEST['entity'] == "leads") {
		$entity_tab = "lead";
		$id_en = "lead";
	} elseif ($_REQUEST['entity'] == "clients_people") {
		$entity_tab = "client_people";
		$id_en = "cl_pe";
	}
	$entity = $_REQUEST['entity'];
	
	//submit records
	if ($_POST['submit']) {
		//get email from selected item
		if ($_REQUEST['item_selected']) {
			$sql = 'SELECT email
			FROM gain_'.$entity_tab.'
			WHERE id_'.$id_en.' IN ('.$_REQUEST['item_selected'].')
			AND removed IS NULL';
			$selected_email_array = $db->GetCol($sql);
			$selected_email = implode('","', $selected_email_array);
		}

		//get email from gain_enews_contact
		$sql = 'SELECT email
		FROM gain_enews_contact
		WHERE removed IS NULL';
		$enews_contact_array = $db->GetCol($sql);

		//get email that's not in gain_enews_contact
		$diff_email = array_diff($selected_email_array, $enews_contact_array);

		//insert that email to gain_enews_contact
		foreach ($diff_email as $k => $v) {
			$sql = 'INSERT INTO gain_enews_contact(email, active, mailing_lists, added, added_by) VALUES("'.$v.'", NOW(), "'.implode(':', $_POST['mailing_list']).':", NOW(), "'.$_SESSION[SESSION_L].'")';
			$db->Execute($sql);
		}

		//get enews list of item
		if ($selected_email) {
			$sql = 'SELECT id_list, email
			FROM gain_enews_contact_list
			WHERE email IN("'.$selected_email.'")';
			$enews_item_list = $db->GetArray($sql);
		}

		//re-format enews item list array
		foreach($enews_item_list as $k => $v) {
			$email_contact1[$v['email']][] = $v['id_list'];
			$email1[] = $v;
		}

		//get enews list from db
		$sql = 'SELECT id_list, email
		FROM gain_enews_contact_list';
		$enews_list = $db->GetArray($sql);

		//re-format enews list from db array
		foreach($enews_list as $k=>$v) {
			$email_contact2[$v['email']][] = $v['id_list'];
		}
		foreach ($selected_email_array as $k => $v) {
			if(!$email_contact2[$v]) {
				foreach ($_POST['mailing_list'] as $k => $check_box_val) {
					$sql = SQL('INSERT INTO gain_enews_contact_list(email, id_list)
					VALUES(%s, %d)', $v, $check_box_val);
					$db->Execute($sql);
				}
			} else {
				foreach ($email_contact1 as $mail => $mailing_list) {
					$merged = array_unique(array_merge($mailing_list, $_POST['mailing_list']));
					$sql = 'DELETE FROM gain_enews_contact_list
					WHERE email = "'.$mail.'"';
					$db->Execute($sql);
					foreach ($merged as $id_list) {
						$sql = SQL('INSERT INTO gain_enews_contact_list(email, id_list)
						VALUES(%s, %d)', $mail, $id_list);
						$db->Execute($sql);
					}
				}
			}
		}
		return 1;
	}
	
	//set item_selected to hidden
	if (is_array($_REQUEST['item_selected'][1])) {
		$item_selected_b = implode(',', $_REQUEST['item_selected'][1]);
	} else { //all
		$item_selected_b = fw_cache_items_get($_REQUEST['entity_token']);
//		$item_selected = gain_entities_get_search_id($_REQUEST['item_selected'], $_POST['entity_token'], 1);
//		$item_selected_b = implode(',', $item_selected);
	}
	$hidden .= '<input type="hidden" name="item_selected" value="'.$item_selected_b.'"/>';

	if ($_REQUEST['entity_token']) {
		$hidden .= '<input type="hidden" name="entity_token" value="'.$_REQUEST['entity_token'].'"/>';
	}

	if ($_REQUEST['entity']) {
		$hidden .= '<input type="hidden" name="entity" value="'.$_REQUEST['entity'].'"/>';
	}

	if ($_REQUEST['group_token']) {
		$hidden .= '<input type="hidden" name="group_token" value="'.$_REQUEST['group_token'].'"/>';
	}

	if ($_REQUEST['filter_as_group']) {
		$hidden .= '<input type="hidden" name="filter_as_group" value="'.$_REQUEST['filter_as_group'].'"/>';
	}

	//set refresh page

	$entity_mod = $_REQUEST['entity'];
	if ($entity_mod == 'clients_people') {
		$entity_refresh = 'crm&search_for=clients_people';
	} else {
		$entity_refresh = 'leads';
	}

	$sql = 'SELECT id_list, list_name
	FROM gain_enews_list
	WHERE removed_by IS NULL ORDER BY list_name';
	$mailing_lists = $db->GetAssoc($sql);
	$mailing_lists = clean($mailing_lists);

	$r = '<div class="popupHeader">'.msg('fw_add_mailing').'</div>
		<div class="detailsInfo">
			<form id="fw_manage_group" action="index.php?ajax=1&mod=entities&view=add_mailing" method="post">
			'.$hidden.'
			<table cellspacing="1" cellpadding="4" width="100%">
				<tr class="fw-form_item"><td style="width: 100px;" class="fw-form_head">'.msg('mailing_list').': </td><td>
				'.form_checkbox('mailing_list', array('values' => $mailing_lists, 'default' => '', 'param1' => '<br/>')).'</td></tr>
				<tr><td colspan="2" align="right"><input type="submit" class="btn medium green awesome btn-add" name="submit" value="submit"/></td></tr>
			</table>
			</form>
		</div>
		<script type="text/javascript">
			$("#fw_manage_group").ajaxForm({
				beforeSubmit: showRequest,
				success: function(data) {
					window.location = "index.php?mod='.$entity_refresh.'&mail=1";
				}
			});
			function showRequest(formData, jqForm, options) {
				$("#fw_manage_group").find("input.awesome").hide().parent().append("<span style=\"line-height: 21px; float: right;\">*Loading...</span>");
			}
	</script>
		';
	return $r;
}

/**
 * get items selected from table ":gain_fw_search_cache"
 *
 * @param unknown_type $items_id
 * @param unknown_type $need_array
 */
function gain_entities_get_search_id($items_id, $token, $need_array = ''){
	global $db;
	if ($items_id[0] == 2) { //select
		$items_id = fw_cache_items_get($token);
	} else {
		$items_id = substr($items_id, 2);
	}
	if ($need_array == 1) {
		$a = explode(',', $items_id);
		return explode(',', $items_id);
	} else {
		return $items_id;
	}
}

/**
 * set for show page
 * Enter description here ...
 * @param unknown_type $entity
 * @param unknown_type $basics
 * @param unknown_type $fields
 * @param unknown_type $mod_client
 */
function gain_entity_set_display($entity, &$basics, $fields, $mod_client = ''){
	$fn_search_form = PREFIX.$basics['entity'].'_search_form';
	$fn_search_result = PREFIX.$basics['entity'].'_search_result';
	$fn_entity_view_zone_detail = PREFIX.$basics['entity'].'_view_zone_detail';
	$fn_entity_view_zone_form = PREFIX.$basics['entity'].'_view_zone_form';

	if ($_REQUEST['link'] == 'add' || $_REQUEST['link'] == 'edit' || $_REQUEST['link'] == 'detail') {
		gain_entity_set_items_submenu_view_zone($basics['entity'], $basics['set_submenu']);
	}

	if ($_REQUEST['link'] == 'edit' || $_REQUEST['link'] == 'add') {
		if ($_REQUEST['link'] == 'edit') {
			if (check_permission('delete', $basics['entity'], '', $basics['id']) != 1) {
				$basics['del_button'] = 1;
			}
		}
		$r = $fn_entity_view_zone_form($entity, $basics, $fields, $mod_client);
	} else if ($_REQUEST['link'] == 'detail') {
		$r = $fn_entity_view_zone_detail($entity, $basics, $fields, $mod_client);
	} else {
		$tabs = gain_entity_set_group($basics['entity'], 1);
		if ($basics['rem_tabs']) {
			foreach ($basics['rem_tabs'] as $k => $v) {
				unset($tabs[$k]);
			}
		}
		if ($tabs && !$_REQUEST['ajax']) {
			//$basics['group_set'] = 1;
			if ($basics['option_not_required'] != 1) {
				gain_entity_set_items_submenu($basics, $tabs, $basics['set_submenu']);
			}
			$acts = array('search_result');
			foreach ($acts as $kx => $act) {
				//add all tabs
				$no_need_tab = 1;

				if (count($tabs) == 1 && $basics['manage_group_set'] == -1) {
					$no_need_tab = 0;//0
				}
				//start div
				$hide = '';
				if ($act == 'search_form') {
					$hide = ' class="hide"';
				}
				if ($no_need_tab == 1) {
					$r .= '<div id="tab_menu_'.$act.'" style="background: #FFF;"><ul'.$hide.'>';
				}
				$default = '';
				$div_id = '';
				$ax = -1;
				$ax = -1;

				if ($basics['manage_group_set'] != -1) {
					$r .= '<li id="manage_entity_group_user_li" rel="'.(++$ax).'" load="0" entity="entities" entity_key="manage_entity_group_user" class="fw-group-icon-fix">
						<a title="'.msg('manage groups').'" href="#manage_entity_group_user_content"><span class="ui-icon ui-icon-folder-collapsed"></span></a>
					</li>';

					$div_id = '';
					if ($_REQUEST['search_for'] == 'manage_entity_group_user') {
						$_REQUEST['entity'] = $_REQUEST['mod'];
						$c = gain_entities_manage_entity_group_user();
					}
					$div_id .= '<div id="manage_entity_group_user_content">'.$c.'</div>';
				}
				$default = '';

				foreach ($tabs as $k => $v) {
					//for the next tabs start with empty value
					unset($_REQUEST['sort_order']);
					unset($_REQUEST['sort_by']);
					unset($basics['group_id']);
					unset($basics['permanent_group']);
					unset($basics['where_condition']);
					$fn = 'gain_'.$basics['entity'].'_'.$act;
					//$fn_search_form = 'gain_'.$basics['entity'].'_search_form';

					$tabs_content_name = $k.'_content';
					++$ax;
					$icon_active_group = '';
					$loaded = 0;
					if ($v['main'] != 1) {
						if ($_REQUEST['search_for'] == $k) {
							$loaded = 0;
						} else {
							if ($v['permanent_group'] != 1) {
								if ($v['num'] > 0) {
									$num = $v['num'];
								} else {
									$num = count($v['group_id_arr']);
								}
								$v['entity_tabs_name'] .= ' <span class="cnt_item"> ('.$num.') </span>';
							}
						}
						if ($v['permanent_group'] != 1) {
							$icon_active_group = '<a class="fg-button fg-button-icon-solo ui-corner-all" style="height: 1px; margin-right:-5px;" onclick="fw_manage_entity_group(this,\''.$v['entity'].'\', \''.$v['entity_key'].'\', \'\', \'active_group\', \'\', \'\', 0)">
								<span class="ui-icon ui-icon-close" style="cursor: pointer; margin-left: -12px;"></span>
								</a>';
						}
					} else {
						if (!isset($_REQUEST['search_for']) || $_REQUEST['search_for'] == $basics['entity']) {
							$loaded = 1;
						}
					}

					if ($no_need_tab == 1) {
						$r .= '<li id="'.$k.'_li" rel="'.$ax.'" class="fw-group-icon-fix" entity="'.$basics['entity'].'" entity_key="'.$k.'" load="'.$loaded.'"><a href="#'.$tabs_content_name.'">'.$v['entity_tabs_name'].$icon_active_group.'</a></li>';
					}
					if ($v['group_id']) {
						$basics['group_id'] = $v['group_id'];
					}
					if ($v['permanent_group'] == 1) {
						$basics['permanent_group'] = 1;
					}
					if ($v['where_condition']) {
						$basics['where_condition'] = $v['where_condition'];
					}

					$div_id .= '<div id="'.$tabs_content_name.'">';
					if ($loaded == 1) {
						if (function_exists($fn)) {
							$div_id .= $fn($k, $basics, $fields);
						} else {
							$div_id = 'Create - '.$fn;
						}
					}
					$div_id .= '</div>';
				}
				if ($no_need_tab == 1) {
					$r .= '</ul>';
				}
				$r .= $div_id;
				//end div
				if ($no_need_tab == 1) {
					$r .= '</div>';
					$r .= '
					<script type="text/javascript">
						$("#tab_menu_'.$act.'").tabs({
							select: function(event, ui){
								var entity = $(ui.tab).parents().attr("entity");
								var entity_key = $(ui.tab).parents().attr("entity_key");
								var load = $(ui.tab).parent().attr("load");
								if (load == 0) {
									if (entity_key == "manage_entity_group_user") {
										load_page_content(\'index.php?ajax=1&mod=\'+entity+\'&view=\'+entity_key+\'&entity='.$_REQUEST['mod'].'\', \'div#\'+entity_key+\'_content\');
									} else {
										load_page_content(\'index.php?ajax=1&mod=\'+entity+\'&entity=\'+entity_key, \'div#\'+entity_key+\'_content\');
									}
									$(ui.tab).parent().attr("load", "1");
								}
								return true;
							}
						});
						$("#tab_menu_'.$act.' ul.ui-tabs-nav li").dblclick(function(){
							var entity = $(this).attr("entity");
							var entity_key = $(this).attr("entity_key");
							if (entity_key == "manage_entity_group_user") {
								load_page_content(\'index.php?ajax=1&mod=\'+entity+\'&view=\'+entity_key+\'&entity='.$_REQUEST['mod'].'\', \'div#\'+entity_key+\'_content\');
							} else {
								load_page_content(\'index.php?ajax=1&mod=\'+entity+\'&entity=\'+entity_key, \'div#\'+entity_key+\'_content\');
							}
							$(this).attr("load", "1");
						});
						';
					if ($_REQUEST['search_for']) {
						$r .= '
						$(document).ready(function(){
							var entity_index = $("li#'.$_REQUEST['search_for'].'_li").attr("rel")*1;
							$("#tab_menu_search_result").tabs("select", entity_index);
						});
						';
					} else {
						if ($basics['manage_group_set'] != -1) {
							$r .= '
							$(document).ready(function(){
								$("#tab_menu_search_result").tabs("select", 1);
							});
							';
						}
					}
					$r .= '
					</script>
					';
				}
			}
		} else {
			if (($_REQUEST['entity'] && $basics['entity'] != $_REQUEST['entity']) || $tabs[$_REQUEST['entity']]['where_condition'] || $basics['dfgf']) {
				$entity = $_REQUEST['entity'];
				$basics['op'] .= '&entity='.$entity;
				//set filter
				$basics['group_id'] = $tabs[$_REQUEST['entity']]['group_id'];
				$basics['where_condition'] = $tabs[$_REQUEST['entity']]['where_condition'];
				$basics['permanent_group'] = $tabs[$_REQUEST['entity']]['permanent_group'];
				$group_url = $tabs[$_REQUEST['entity']]['group_url'];
				if ($group_url) {
					$basics['group_url'] = 1;
				}
				$a = explode('&search_for=' . $_REQUEST['entity'], $group_url);
				parse_str($a[1], $parsed);
				//keep tmp
				if ($_REQUEST[$_REQUEST['entity']]) {
					$tmp_req = $_REQUEST[$_REQUEST['entity']];
				}
				$_REQUEST = array_merge($_REQUEST, $parsed);
				$_REQUEST['default'] = $parsed;
				if ($tmp_req) {
					foreach ($tmp_req as $k => $v) {
						if (!$_REQUEST[$k] && $v != '') {
							$_REQUEST[$_REQUEST['entity']][$k] = $v;
						}
					}
				}
			}

			if (function_exists($fn_search_form)) {
				$search_form = $fn_search_form($entity, $basics, $fields, $mod_client);
			}

			if (function_exists($fn_search_result)) {
				$search_listing = $fn_search_result($entity, $basics, $fields, $mod_client);
			}

			if ($_REQUEST['link'] == 'search_result') {
				$search_form = '';
			}
			$r = $search_form . $search_listing;
		}
	}
	$re_act = gain_entities_show_re_act($basics['entity'], 1);
	return $re_act.$r;
}

/**
 * move to fw/entity.php
 * @return group array
 * @param unknown_type $entity
 */
function gain_entity_set_group($entity, $active = '') {
	global $db, $cache_user;
	//check tabs from table
	//set submenu
	//all tabs
	$sql = SQL('SELECT group_token, group_name, share, entity, added_by, where_condition, permanent_group, num, group_url, permanent_order, manage_access, manage_permission
	FROM gain_fw_entity_group
	WHERE removed IS NULL
	AND entity=%s
	ORDER BY permanent_order DESC', $entity);
	$tabs_all = $db->GetAssoc($sql);

	$sql = SQL('SELECT group_token, group_order, group_active
	FROM gain_fw_entity_group_user
	WHERE id_user=%d
	AND entity=%s', $_SESSION[SESSION_L], $entity);
	$tabs_status = $db->GetAssoc($sql);
	if ($tabs_all) {
		foreach ($tabs_all as $k => $v) {
			if ($v['permanent_order'] > 0 && ++$j == 1) {
				$max_order = $v['permanent_order'];
			}
			$keep = 1;
			//active,
			$k_order = $max_order + $tabs_status[$k]['group_order'];
			if ($v['permanent_group'] == 1) {
				$keep = 1;
				$k_order = $v['permanent_order'];
			} else if ($active == 1) {
				if ($tabs_status[$k]['group_active'] != 1) {
					$keep = 0;
				}
			}
			
			if ($v['manage_access'] == 'department') {
				if ($_SESSION[SESSION_A]['department'] != $cache_user[$v['added_by']]['id_department']) {
					$keep = 0;
				}
			}

			if ($v['added_by'] != $_SESSION[SESSION_L] && $v['share'] != 1 && $v['permanent_group'] != 1) {
				$keep = 0;
			}

			if ($keep == 1) {
				++$order;
				$rsl[$order]['entity_key'] = $k;
				$rsl[$order]['group_name'] = clean($v['group_name']);
				$rsl[$order]['entity'] = $v['entity'];
				$rsl[$order]['added_by'] = $v['added_by'];
				$rsl[$order]['num'] = $v['num'];
				$rsl[$order]['group_url'] = $v['group_url'];
				$rsl[$order]['share'] = $v['share'];
				$rsl[$order]['permanent_group'] = $v['permanent_group'];
				$rsl[$order]['where_condition'] = $v['where_condition'];

				$rsl[$order]['group_active'] = $tabs_status[$k]['group_active'];
				$rsl[$order]['group_order'] = $k_order;
				
				$rsl[$order]['manage_access'] = $v['manage_access'];
				$rsl[$order]['manage_permission'] = $v['manage_permission'];
				$group_token_list[] = $k;
			}
		}
		sort_array_2d($rsl, 'group_order');
	}

	$entities_req[$entity] = array(
		'main' => 1,
		'entity_key' => $entity,
		'entity_tabs_name' => msg('menu_'.$entity),//set msg
		'entity' => $entity,
	);

	if ($rsl) {
		//get group id
		$sql = SQL('SELECT group_token, group_id
		FROM gain_fw_entity_group_item
		WHERE group_token IN("'.implode('","', $group_token_list).'")');
		$group_id_arr = $db->GetArray($sql);

		if ($group_id_arr) {
			foreach ($group_id_arr as $k => $v) {
				$group_id_arr_list[$v['group_token']][] = $v['group_id'];
			}
		}

		foreach ($rsl as $k => $v) {
			$group_id = '';
			if ($group_id_arr_list[$v['entity_key']]) {
				$group_id = implode(',', $group_id_arr_list[$v['entity_key']]);
			}
			if ($v['permanent_group'] != 1) {
				$entities_req[$v['entity_key']]['main'] = 0;
			}
			$entities_req[$v['entity_key']]['entity_key'] = $v['entity_key'];
			$entities_req[$v['entity_key']]['entity_tabs_name'] = $v['group_name'];
			$entities_req[$v['entity_key']]['group_id'] = $group_id;
			$entities_req[$v['entity_key']]['group_id_arr'] = $group_id_arr_list[$v['entity_key']];
			$entities_req[$v['entity_key']]['entity'] = $v['entity'];
			$entities_req[$v['entity_key']]['group_active'] = $v['group_active'];
			$entities_req[$v['entity_key']]['id_user'] = $v['added_by'];
			$entities_req[$v['entity_key']]['share'] = $v['share'];
			$entities_req[$v['entity_key']]['permanent_group'] = $v['permanent_group'];
			$entities_req[$v['entity_key']]['where_condition'] = $v['where_condition'];
			$entities_req[$v['entity_key']]['num'] = $v['num'];
			$entities_req[$v['entity_key']]['group_url'] = $v['group_url'];
				
			$entities_req[$v['entity_key']]['manage_access'] = $v['manage_access'];
			$entities_req[$v['entity_key']]['manage_permission'] = $v['manage_permission'];
		}
	}
	return $entities_req;
}

/**
 * @return listing param
 * @param unknown_type $entity
 * @param unknown_type $basics
 * @param unknown_type $fields
 * @param unknown_type $table
 * @param unknown_type $entity_tabs
 */
function gain_entity_set_table_list($entity, &$basics, $fields, $table, $entity_tabs = ''){
	if (!strstr($basics['op'], 'entity=')) {
		$basics['op'] .= '&entity='.$entity;
	}

	//change this part call search form function just one time!
	$fn_search_form = PREFIX.$basics['entity'].'_search_form';
	if (function_exists($fn_search_form)) {
		$entities = $fn_search_form($entity, $basics, $fields, $entity_tabs, 1);
	}

	$entities[$basics['entity']]['table'] = $table;
	//return form and search query!
	$search = fw_search_form($entities, $basics['entity']);

	$basics['history_icon'] = $search['history_icon'];

	if ($basics['link_default'] == 1) {
		$search['linked'] .= '&link_default=1';
	}
	if ($_REQUEST['item_id']) {
		$search['linked'] .= '&item_id=' . $_REQUEST['item_id'];
	}
	//$basics['linked'] = $search['linked'].$search['sort'];
	$entities[$basics['entity']]['basics']['linked'] = $basics['linked'] = $search['linked'].$search['sort'];

	//query add for sorting
	$sql_limit_page = fw_list_sort_limit($entities[$basics['entity']]['table']['headers2'], $entities[$basics['entity']]['table']['default_sort'], $entity);

	if ($basics['entity'] != $basics['entity_key'] || $basics['where_condition'] != '' || $basics['group_url']) {
		if ($basics['where_condition'] != '') {
			$sql_add .= $basics['where_condition'];
		} else if (!$basics['group_url']) {
			if ($basics['group_id'] != '') {
				$sql_add .= SQL(' AND '.$basics['table'].'.'.$basics['key'].' IN('.$basics['group_id'].')');
			} else {
				$sql_add .= ' AND 1=2';
			}
		}
	}
	if ($basics['sql_add']) {
		$sql_add .= $basics['sql_add'];
	}
	
	//add sql
	if ($_REQUEST['export'] == 1 && $basics['enable_export'] == 1) {
		//set item_selected to hidden
		if ($_REQUEST['item_selected'][1]) {
			$item_selected = $_REQUEST['item_selected'][1];
		} else { //all
			$item_selected = gain_entities_get_search_id($_REQUEST['item_selected'][0].',', $_REQUEST['entity_token']);
		}
		$sql_add .= ' AND ' . $basics['table'] . '.' . $basics['key'] . ' IN('.$item_selected.')';
	}

	$search_result = fw_search_result($entities, $basics['entity'], $search, $sql_limit_page, $sql_add);

	if ($_REQUEST['link'] == 'show_sql' || $basics['show_sql'] == 1) {
		echo $search_result['sql_list'];
	}

	if ($entities[$basics['entity']]['table']['headers2']) {
		$headers = $entities[$basics['entity']]['table']['headers2'];
	} else {
		$headers = $entities[$basics['entity']]['table']['headers'];
	}

	$default_sort = $entities[$basics['entity']]['table']['default_sort'];
	$header_def = $entities[$basics['entity']]['table']['header_def'];
	$basics['search'] = $search_result['search'];
	if ($entities[$entity]['basics']['search']) {
		$basics['search'] += $entities[$entity]['basics']['search'];
	}
	//set link for header sorter
	$add_link = 'mod='.$basics['op'].'&amp;'.$entity.'[sort_by]={sort_by}&amp;'.$entity.'[sort_order]={sort_order}'.$search['linked'];

	if ($basics['link_default'] == 1) {
		$add_link .= '&link_default=1';
	}
	//set header name with link
	$basics['header_name'] = fw_headers($headers, $entity, $fields, $header_def, $add_link, '#'.$basics['refresh_action_ajax']);//'#'.$basics['entity_key'].'_content'

	//set show data for each row
	$basics['pattern'] = $search_result['pattern'];

	//set icon new
	$basics['data_values'] = $search_result['data_values'];

	//show word after action
	//$re_act .= gain_entities_show_re_act($basics['entity'], 1);
	$basics['search_form'] = $search['form'] . $re_act;
	$basics['pagination'] = fw_paged_results_js(msg('pages').': ', $entity, $search_result['item_all'], 'mod='.$basics['op'].$search['linked'].$search['sort'], $default_sort['limit'], '#'.$basics['refresh_action_ajax']);
	//new rq 04 05 2011: keep item num to group
	if (!$_REQUEST['search']) {
		if ($basics['entity'] != $entity) {
			//echo (int)$search_result['item_all'] . $basics['entity'] .'|'. $entity;
			$param_qry = array(
				'table' => 'gain_fw_entity_group',
				'cols' => array(
					'num', '%s', $search_result['item_all'],
				),
				'where' => SQL('group_token=%s', $entity),
			);
			db_query($param_qry, 1, 'fw');
		}
	}

	$basics['add_js_script'] = '
	<script type="text/javascript">
		$(document).ready(function(){
			$("div[id^=tab_menu][id$=search_result]").find("#'.$entity.'_li a span.cnt_item").remove();
			$("div[id^=tab_menu][id$=search_result]").find("#'.$entity.'_li a").append("<span class=\"cnt_item\"> ('.(int)$search_result['item_all'].') '.'</span>");
			//$("#tab_menu_search_result #'.$entity.'_li a span.cnt_item").remove();
			//$("#tab_menu_search_result #'.$entity.'_li a").append("<span class=\"cnt_item\"> ('.(int)$search_result['item_all'].') '.'</span>");
			gain_init("'. $entity .'_search_result");
		});
	</script>';
}

/**
 *
 * Enter description here ...
 * @param $entity
 * @param $entity_tabs
 */
function gain_entities_items_tabs($entity, $entity_tabs){
	global $db, $cm_menu, $global_config;
	$_REQUEST['id'] = (int)$_REQUEST['id'];
	if ($global_config['entity']['tab_index']) {
		$js_tab_index_color = ' var tab_index_colors = new Array();' ."\n";
		foreach ($global_config['entity']['tab_index'] as $k => $v) {
			$js_tab_index_color .= 'tab_index_colors['. (int)$k .'] = "'. $v .'" ;' ."\n";
		}
		$tab_index_key = array_keys($global_config['entity']['tab_index']);
	}

	//show tabs
	if ($entity_tabs && $_SESSION[SESSION_P]['access']['tabs'][$entity]) {
		$r .= '<div id="tab_menu" mod="'.$entity.'" item_id="'.$_REQUEST['id'].'"><ul>';
		$div_id = '';
		$i = -1;
		$tab_index_number = gain_tab_index_get($entity, $_REQUEST['id']);
		$k_page = 0;
		$search_for = array();
		foreach ($entity_tabs as $k => $v) {
			if ($cm_menu['S'][$entity][$k]['access']) {
				++$k_page;
				unset($index);
				$index_show = '';
				$fn = 'gain_'.$entity.'_'.$k;
				//show loading
				$content = '';
				//check load
				$load = 0;

				if ($v['load'] == 1 && $k_page > 1) {
					$search_for[] = $k;
				}

				if ($k_page == 1 && !$_REQUEST['search_for']) {
					$_REQUEST['search_for'] = $k;
				}

				$index = $tab_index_number[$k];

				$index_style = '';

				if ($index['qty'] == 0) {
					$index['qty'] = '';
					$qty = '';
				} else {
					if ($index['date_diff'] >= $tab_index_key[2]) {
						$c = 60;
					} else if ($index['date_diff'] >= $tab_index_key[1]) {
						$c = 21;
					} else {
						$c = 4;
					}
					$color = $global_config['entity']['tab_index'][$c];
					$index_style = ' class="fw-tab-index" style="color: ' . $color . ';background-color: ' . $color . ';"';
					$qty = '0';
				}
				//' . $index['qty'] . 'color: ' . $color . ';
				$index_show = '<span name="' . $k . '"' . $index_style . ' title="'.msg('Last updated') . ': ' . format_date_time($index['date_updated']).'"> </span>';//'.$qty.'

				$v['head'] = strip_tags($v['head']);
				if (!$v['head']) {
					$v['head'] = msg($k);
				}
				$r .= '<li load="' . $load . '" view="' . $k . '" id="m_' . $k . '_li" rel="' . (++$i) . '"><a href="#' . $k . '">' . $v['head'] . '</a>' . $index_show . '</li>';
				$div_id .= '<div id="' . $k . '">' . $content . '</div>';
			}
		}

		$r .= '</ul>'.$div_id.'
		</div>
		<script type="text/javascript">
			' . $js_tab_index_color . '
				$("#tab_menu").tabs({
					select: function(event, ui){
						var item_id = $(ui.tab).parents("#tab_menu").attr("item_id");
						var mod = $(ui.tab).parents("#tab_menu").attr("mod");
						var load = $(ui.tab).parent().attr("load");
						var view = $(ui.tab).parent().attr("view");

						if (load == 0) {
							load_page_content(\'index.php?ajax=1&mod=\'+mod+\'&view=\'+view+\'&item_id=\'+item_id, \'div#\'+view);
							$(ui.tab).parent().attr("load","1");
						}
						return true;
					},
					selected: -1
				});
				$(document).ready(function(){
					$("#tab_menu ul.ui-tabs-nav li").dblclick(function(){
						var item_id = $(this).parents("#tab_menu").attr("item_id");
						var mod = $(this).parents("#tab_menu").attr("mod");
						var load = $(this).attr("load");
						var view = $(this).attr("view");

						load_page_content(\'index.php?ajax=1&mod=\'+mod+\'&view=\'+view+\'&item_id=\'+item_id, \'div#\'+view);
						$(this).attr("load","1");
					});
					';

					if ($search_for) {
						foreach ($search_for as $k => $v) {
							$r .= '
							var entity_index = $("li#m_' . $v . '_li").attr("rel")*1;
							$("#tab_menu").tabs("select", entity_index);
							';
						}
					}

					//for load tabs menu
					if ($_REQUEST['search_for']) {
						$r .= '
						var entity_index = $("li#m_' . $_REQUEST['search_for'] . '_li").attr("rel")*1;
						$("#tab_menu").tabs("select", entity_index);
						return false;
						';
					}
					$r .= '
				});
			';
		$r .= '
		</script>';
	}
	return $r;
}

function gain_entity_get_entity_detail($entity = '', $key = ''){
	global $cache_entity;
	if ($cache_entity) {
		foreach ($cache_entity as $k => $v) {
			$entity_details[$v['module']] = array('entity_id' => $k) + $v;
		}
	}
	if ($entity == '') {
		return $entity_details;
	} else if ($key == '') {
		return $entity_details[$entity];
	} else {
		return $entity_details[$entity][$key];
	}
}

function gain_entities_manage_permission(){
	global $db, $cache_department;
	$entity = $_REQUEST['entity'];
	$entity_id = $_REQUEST['entity_id'];
	$entity_info = gain_entity_get_entity_detail($entity);
	$options_list = array(
		'p_view' => msg('permission_view'),
		'p_modify' => msg('permission_modify'),
		'p_delete' => msg('permission_delete')
	);

	if ($_POST['transfer']) {
		$id_owner_new = $_POST['id_owner_new'];
		//update new owner id to main table

		$param_qry = array(
			'table' => PREFIX.$entity_info['table_name'],
			'cols' => array(
				'dept_owner', '%d', $id_owner_new,
			),
			'where' => $entity_info['field_id'].'='.$entity_id,
		);
		db_query($param_qry);

		//update gain_entity_permission
		$access_id_arr[] = $_POST['owner'];
		$access_id_arr[] = $id_owner_new;

		$sql = SQL('DELETE FROM gain_entity_permission
		WHERE entity=%s
		AND entity_id=%d
		AND access_type="D"
		AND access_id IN('.implode(',', $access_id_arr).')', $entity, $entity_id);
		$db->Execute($sql);

		$param_qry = array(
			'table' => 'gain_entity_permission',
			'cols' => array(
				'entity', '%s', $entity,
				'entity_id', '%d', $entity_id,
				'access_type', '%s', 'D',
				'access_id', '%d', $id_owner_new,
				'p_view', '%d', 1,
				'p_modify', '%d', 1,
				'p_delete', '%d', 1
			),
		);
		db_query($param_qry);
		$notify = fw_notify_msg('transfer update');
	} else if ($_POST['link'] == msg('Transfer Ownership')) {
		if ($cache_department) {
			foreach ($cache_department as $id_department => $v) {
				if ($id_department != $_POST['owner']) {
					$department_list[$id_department] = $v['department_name'];
				}
			}
			asort($department_list);
		}
		$r = '<form method="post" action="index.php?mod=entities&view=manage_permission&ajax=1" id="form_manage_permission">
			<input type="hidden" name="entity" value="'.$entity.'"/>
			<input type="hidden" name="entity_id" value="'.$entity_id.'"/>
			<input type="hidden" name="owner" value="'.$_POST['owner'].'"/>
			' . msg('New owner') . ': ' . form_select('id_owner_new', array('values' => $department_list, 'req' => 1)).'
			<br class="clr"/>
			<br class="clr"/><input type="submit" name="transfer" value="'.msg('TRANSFER').'" class="btn medium green awesome"/>
			<input type="submit" name="cancel" value="'.msg('CANCEL').'" class="btn medium blue awesome" style="float: right;"/>
		</form>
		<script type="text/javascript">
			$(document).ready(function(){
				$("#form_manage_permission").ajaxForm({
					target: ".popContent",
				});
			});
		</script>';
		return $r;
		exit;
	} else if ($_POST['submit']) {
		$sql = SQL('DELETE FROM gain_entity_permission WHERE entity=%s AND entity_id=%d', $entity, $entity_id);
		$db->Execute($sql);

		if ($_POST['owner'] > 0) {
			$param_qry = array(
				'table' => 'gain_entity_permission',
				'cols' => array(
					'entity', '%s', $entity,
					'entity_id', '%d', $entity_id,
					'access_type', '%s', 'D',
					'access_id', '%d', $_POST['owner'],
					'p_view', '%d', 1,
					'p_modify', '%d', 1,
					'p_delete', '%d', 1,
				),
			);
			db_query($param_qry);
		}

		if ($_POST['dept']) {
			foreach ($_POST['dept'] as $id_department => $v) {
				if ($_POST['permission'][$id_department]) {
					$param_qry = array(
						'table' => 'gain_entity_permission',
						'cols' => array(
							'entity', '%s', $entity,
							'entity_id', '%d', $entity_id,
							'access_type', '%s', 'D',
							'access_id', '%d', $id_department,
							'p_view', '%d', 1,
							'p_modify', '%d', $_POST['permission'][$id_department]['p_modify'],
							'p_delete', '%d', $_POST['permission'][$id_department]['p_delete']
						),
					);
					db_query($param_qry);
				} else {
					$param_qry = array(
						'table' => 'gain_entity_permission',
						'cols' => array(
							'entity', '%s', $entity,
							'entity_id', '%d', $entity_id,
							'access_type', '%s', 'D',
							'access_id', '%d', $id_department,
							'p_view', '%d', 1,
							'p_modify', '%d', 0,
							'p_delete', '%d', 0
						),
					);
					db_query($param_qry);
				}
			}
		}

		$notify = fw_notify_msg('permission update');
	}

	//get owner
	$sql = 'SELECT dept_owner, CONCAT_WS(" ", '.$entity_info['field_select'].') AS name
	FROM '.PREFIX.$entity_info['table_name'].'
	WHERE '.$entity_info['field_id'].'='.$entity_id;
	$entity_detail = $db->GetRow($sql);
	$department_owner = $entity_detail['dept_owner'];

	//get save data
	$sql = SQL('SELECT access_id, p_view, p_modify, p_delete
	FROM gain_entity_permission
	WHERE access_type="D"
	AND entity=%s
	AND entity_id=%d', $entity, $entity_id);
	$permission_default = $db->GetAssoc($sql);

	$r = '<div class="popupHeader">'.msg('Permissions').'</div>
	<div id="manage_permission_notify">' . $notify . '<h3>'.clean($entity_detail['name']).'</h3>';
	$r .= '<form method="post" action="index.php?mod=entities&view=manage_permission&ajax=1" id="form_manage_permission">
	<input type="hidden" name="entity" value="'.$entity.'"/>
	<input type="hidden" name="entity_id" value="'.$entity_id.'"/>
	<input type="hidden" name="owner" value="'.$department_owner.'"/>';

	if ($cache_department) {
		foreach ($cache_department as $id_department => $inf) {
			$owner = '';
			$disabled = 0;
			$hide[$id_department] = ' class="hide"';
			if ($permission_default[$id_department]) {
				$default[$id_department] = 1;
			}
			if ($department_owner == $id_department) {
				$owner = ' ('.msg('owner').')';
				$default[$id_department] = 1;
				$disabled = 1;
			}
			$r .= form_checkbox('dept['.$id_department.']',
				array(
					'values' => array(1 => $inf['department_name'] . $owner),
					'single' => 1,
					'default' => $default[$id_department],
					'disabled' => $disabled,
					'addon_field' => ' onclick="$(\'#m_'.$id_department.'\').toggle().find(\'input:first\').attr(\'checked\', true).attr(\'disabled\', true);"',
				)
			);

			if ($options_list) {
				foreach ($options_list as $k => $v) {
					$disabled = 0;
					if ($k == 'p_view') {
						$disabled = 1;
					}
					$options[$id_department] .= form_checkbox('permission['.$id_department.']['.$k.']',
						array(
							'values' => array(1 => $v),
							'default' => array($permission_default[$id_department][$k]),
							'single' => 1,
							'disabled' => $disabled
						)
					);
				}

			}
			$hide[$id_department] = ' class="hide"';
			if ($permission_default[$id_department] && $department_owner != $id_department) {
				$hide[$id_department] = '';
			}

			$r .= '<div id="m_'.$id_department.'"'.$hide[$id_department].' style="margin-left: 20px;">'.$options[$id_department].'</div>';
		}
	}
	$r .= '<input type="submit" name="submit" value="save" class="btn medium green awesome btn-add"/> <input type="submit" name="link" value="'.msg('Transfer Ownership').'" class="btn medium blue awesome" style="float: right;"/>';
	$r .= '</form>
	<script type="text/javascript">
		$(document).ready(function(){
			$("#form_manage_permission").ajaxForm({
				target: "#manage_permission_notify",
			});
		});
	</script>
	</div>';

	return $r;
}

function gain_entities_search_result_set() {
	global $db, $cm_menu;

	//TODO
	$entity_mod = $_REQUEST['entity_mod'];
	$entity_key = $_REQUEST['entity_key'];
	if ($entity != $entity_mod && $entity_mod != 'settings' && $entity_mod != 'newsletter' && $_REQUEST['item_id'] && $entity_mod != 'entities' && $entity_mod != '') {
		//$entity_key .= '_' . $entity_mod;
	}

// 	if (($cm_menu['M'][$_REQUEST['entity']]['M'] != $_REQUEST['entity_mod'] && $_REQUEST['entity_mod'] != 'entities' && $_REQUEST['entity_mod'] != '' && $_REQUEST['entity_mod'] != $_REQUEST['entity'] && $_REQUEST['entity_mod'] != 'settings') || $_REQUEST['item_id']) {
// 		$entity_key .= '_' . $_REQUEST['entity_mod'];
// 	}

	$sql = SQL('SELECT field_name, sort_field
	FROM gain_fw_search_result
	WHERE entity=%s
	AND entity_key=%s
	AND id_user=%d
	ORDER BY sort_field DESC', $_REQUEST['entity'], $entity_key, $_SESSION[SESSION_L]);
	$info = $db->GetAssoc($sql);

	if ($info[$_REQUEST['field']]) {
		$param_qry = array(
			'table' => 'gain_fw_search_result',
			'cols' => array(
				'field_width', '%s', $_REQUEST['width'],
			),
			'where' => SQL('field_name=%s AND entity=%s AND entity_key=%s AND id_user=%d', $_REQUEST['field'], $_REQUEST['entity'], $entity_key, $_SESSION[SESSION_L]),
		);
	} else {
		$sort_order = max($info);
		$param_qry = array(
			'table' => 'gain_fw_search_result',
			'cols' => array(
				'field_name', '%s', $_REQUEST['field'],
				'entity', '%s', $_REQUEST['entity'],
				'entity_key', '%s', $entity_key,
				'field_width', '%s', $_REQUEST['width'],
				'id_user', '%d', $_SESSION[SESSION_L],
				'sort_field', '%s', $sort_order,
			)
		);
	}
	db_query($param_qry);
}

function gain_entities_search_result_fields(&$fields) {
	$fields['added'] = array('head' => msg('added'), 'type' => 'date', 'values' => 'datetime');
	$fields['added_by'] = array('head' => msg('added by'), 'type' => 'user');
	$fields['updated'] = array('head' => msg('updated'), 'type' => 'date', 'values' => 'datetime');
	$fields['updated_by'] = array('head' => msg('updated by'), 'type' => 'user');
}

function gain_entities_search_result_manage() {
	global $db, $cm_menu;
	$debug_field = 0;
	$entity = $_REQUEST['entity'];
	$entity_key = $_REQUEST['entity_key'];
	$entity_mod = $_REQUEST['entity_mod'];
	$item_id = $_REQUEST['item_id'];
	if (file_exists('modules/' . $entity_mod . '.php')) {
		require_once 'modules/' . $entity_mod . '.php';
		$fn = 'gain_'.$entity.'_search_form';
		if (function_exists($fn)) {
			$basics['entity'] = $entity;
			$entity_info = $fn($entity, $basics, $fields, '', 1);
			$link = $entity_info[$entity]['search']['action_search_form'];
		}
	}
	
	//TODO
	$entity_key = $_REQUEST['entity_key'];
	if ($entity != $entity_mod && $entity_mod != 'settings' && $entity_mod != 'newsletter' && $_REQUEST['item_id'] && $entity_mod != 'entities' && $entity_mod != '') {
		//$entity_key .= '_' . $entity_mod;
	}
// 	if (($entity != $entity_mod && $cm_menu['M'][$entity]['M'] != $_REQUEST['entity_mod'] && $entity_mod != 'entities' && $entity_mod != '' && $entity_mod != 'settings' && $entity_mod != 'newsletter') || $_REQUEST['item_id']) {
// 		$entity_key .= '_' . $entity_mod;
// 	}
	if ($_REQUEST['submit']) {
		$sql = SQL('DELETE FROM gain_fw_search_result WHERE entity=%s AND entity_key=%s AND id_user=%d', $entity, $entity_key, $_SESSION[SESSION_L]);
		$db->Execute($sql);

		if ($_REQUEST['submit'] == "submit") {
			if ($_REQUEST['column_active']) {
				foreach ($_REQUEST['column_active'] as $f => $w) {
					$param_qry = array(
						'table' => 'gain_fw_search_result',
						'cols' => array(
							'entity', '%s', $entity,
							'entity_key', '%s', $entity_key,
							'id_user', '%d', $_SESSION[SESSION_L],
							'field_name', '%s', $f,
							'field_width', '%s', $w,
							'header', '%s', $_REQUEST['header'][$f],
							'sort_field', '%d', ++$i,
							'advanced_options', '%s', serialize($_REQUEST['search_result_options'][$f]),
						),
					);
					db_query($param_qry);
				}
			}
		}
	}

	//get default field from result table
	if (file_exists('modules/'.$entity.'.php')) {
		require_once 'modules/'.$entity.'.php';
	} else if (file_exists('modules/'.$_REQUEST['entity_mod'].'.php')){
		require_once 'modules/'.$_REQUEST['entity_mod'].'.php';
	}
	$main_fn = PREFIX . $entity;

	$search_result_fn = $main_fn.'_search_result';
	//get basics & fields
	if (!function_exists($main_fn)) {
		require_once 'modules/' . $_REQUEST['entity_mod'] . '.php';
		$main_fn = PREFIX . $_REQUEST['entity_mod'] . '_'. $entity;
	}

	$entities = $main_fn('search_result', 1);
	$basics = $entities[$entity]['basics'];
	$fields = $entities[$entity]['fields'];
	$cleanVar = fw_data_cleanup($fields, $basics);
	$fields  = $cleanVar[0];
	$basics  = $cleanVar[1];

	//get definition of search result
	if (function_exists($search_result_fn)) {
		$entities2 = $search_result_fn($entity, $basics, $fields, '', 1);
		$table = $entities2['table'];
	} else {
		$table = $entities['table'];
	}

	//more fields
	gain_entities_search_result_fields($fields);
	//get user define
	$default = gain_entities_search_result_get($basics['entity'], $basics, $fields, $table, 1);

	if ($basics['custom_search_result'] || $default) {
		if ($basics['entity'] != $entity_key) {
			$sql = 'SELECT group_name FROM gain_fw_entity_group WHERE group_token="'.$entity_key.'"';
			$group = $db->GetOne($sql);
		} else {
			$group = msg($entity_key);
		}

		if ($group == '') {
			$group = msg($basics['entity']);
		}

		$r = '<div class="popupHeader">' . msg('manage grid') . ': ' . $group . '</div>
		<div class="detailsInfo">';

		$r .= '<form id="fw_manage_search_result_form">
		<input type="hidden" name="entity_mod" value="'.$entity_mod.'"/>
		<input type="hidden" name="item_id" value="'.$item_id.'"/>
		<table width="100%" cellspacing="1" cellpadding="4">
		<tr>
			<td>
				<input style="float: left;" class="btn medium blue awesome" type="button" value="' . msg('restore') . '" onClick="fw_manage_search_result_save(\''.$entity.'\', \''.$_REQUEST['entity_key'].'\', \''.$entity_mod.'\', \''.$_REQUEST['item_id'].'\', \'restore\', \''.$link.'\');"/>
				<input style="float: right; margin-right: 5px;" class="btn medium gray awesome btn-cancel" type="button" value="' . msg('cancel') . '"  onClick="closePopup();"/>
				<input style="float: right; margin-right: 5px;" class="btn medium green awesome btn-add" type="button" value="' . msg('save') . '" onClick="fw_manage_search_result_save(\''.$entity.'\', \''.$_REQUEST['entity_key'].'\', \''.$entity_mod.'\', \''.$_REQUEST['item_id'].'\', \'submit\', \''.$link.'\');"/>
			</td>
		</tr>
		<tr><td>

		' . fw_notify_msg('notify manage column', 'info', array('style' => 'width: 600px; padding: 0.7em;')) . '
		<ul id="fw_manage_search_result_order">
		<li class="manage_grid_title">
		<div style="width: 221px;">' . msg('default title') . '</div>
		<div style="width: 40px;">' . msg('show field') . '</div>
		<div style="width: 180px;">
			<p class="input_align_h">
				<input type="checkbox" name="custom_title" class="brd0" id="check-custom_title" onClick="$(\'.search_result_name\').find(\'input\').toggle();">
				<label for="check-custom_title">&nbsp;' . msg('custom title') . '</label></div>
			</p>
		<div>
			<p class="input_align_h">
				<input type="checkbox" name="ad_options" class="brd0" id="check-ad_options" onClick="$(\'.search_result_options\').children().toggle();">
				<label for="check-ad_options">&nbsp;' . msg('show advanced properties') . '</label></div><br class="clr"/>
			</p>
		</li>';
		if ($default) {
			foreach ($default as $k => $v) {
				if ($k != 'options' && $k != 'checkbox') {
					$fields[$k]['advanced_options'] = $v['advanced_options'];
					$fields[$k]['head'] = strip_tags($fields[$k]['head']);
					$head_display = $fields[$k]['head'];
					if (trim($basics['custom_search_result'][$k]['header_def']) != '') {
						$head_display = $basics['custom_search_result'][$k]['header_def'];
					} else if (trim($basics['custom_search_result'][$k]['header_tmp']) != '') {
						$head_display = $basics['custom_search_result'][$k]['header_tmp'];
					}
					if ($debug_field == 1) {
						$a = '';
						if ($basics['custom_search_result'][$k]) {
							$a = '*';
						}
						$head_display = $a.$head_display.'<br/>['.$k.']<br/>#'.$fields[$k]['type'];
					}

					$r .= '<li>
							<div><img src="im/sort.png" class="move_me" style="cursor: move; padding-top: 3px;" /></div>
							<div style="width: 180px; line-height: 23px;" header="' . $fields[$k]['head'] . '">'.$head_display.'</div>
							<div style="width: 40px;">
								<p class="input_align_h" style="padding-top: 2px;">
								<input type="checkbox" value="'.$v['width'].'" name="column_active['.$k.']" class="brd0" id="check-column_active-'.$k.'" checked>
								<label for="check-column_active-'.$k.'">&nbsp;</label>
								</p>
							</div>
							<div class="search_result_name" style="width: 180px;">
								' . form_input('header['.$k.']', array('default' => $v['header_def'], 'param1' => 150)) . '&nbsp;
							</div>
							<div class="search_result_options">
								' . gain_entities_search_result_options($k, $fields[$k], $basics) . '&nbsp;
							</div>
						</li>';
					$tmp[$k] = 1;
				}
			}
		}
		$r .= '</ul>
			<hr/>';
		$r .= '<ul id="fw_manage_search_result_order2">';

		//sort_array_2d($basics['custom_search_result'], 'header_def');
		if ($basics['custom_search_result']) {
			foreach ($basics['custom_search_result'] as $k => $v) {
				if (!$tmp[$k] && $k != 'options') {
					$tmp[$k] = 1;
					$fields[$k]['head'] = strip_tags($fields[$k]['head']);
					$head_display = $fields[$k]['head'];
					if (trim($v['header_def']) != '') {
						$head_display = $v['header_def'];
					} else if (trim($v['header_tmp']) != '') {
						$head_display = $v['header_tmp'];
					}

					if ($debug_field == 1) {
						$a = '';
						if ($basics['custom_search_result'][$k]) {
							$a = '*';
						}
						$head_display = $a.$head_display.'<br/>['.$k.']<br/>#'.$fields[$k]['type'];
					}
					$r_list[$head_display] = '<li>
							<div><img src="im/sort.png" class="move_me" style="cursor: move; padding-top: 3px;" /></div>
							<div style="width: 180px; line-height: 23px;" header="' . $v['head'] . '">'.$head_display.'&nbsp;</div>
							<div style="width: 40px;">
								<p class="input_align_h" style="padding-top: 2px;">
									<input type="checkbox" value="'.$default[$k]['width'].'" name="column_active['.$k.']" class="brd0" id="check-column_active-'.$k.'">
									<label for="check-column_active-'.$k.'">&nbsp;</label>
								</p>
							</div>
							<div class="search_result_name" style="width: 180px;">
								' . form_input('header['.$k.']', array('default' => '', 'param1' => 150)) . '&nbsp;
							</div>
							<div class="search_result_options">
								' . gain_entities_search_result_options($k, $fields[$k], $basics) . '&nbsp;
							</div>
						</li>';
				}
			}
		}

		if ($fields) {
			foreach ($fields as $k => $v) {
				if ($v['type'] != 'textarea' && $v['type'] != 'checkbox' && $v['type'] != 'head' && $k != 'phone_number' && $v['search_result'] != 1 && !$tmp[$k]) {
					$n = $ky++;
					$v['head'] = strip_tags($v['head']);
					if ($v['vhead']) {
						if (is_array($v['vhead'])) {
							$head_display = implode(',', $v['vhead']);
						} else {
							$head_display = $v['vhead'];
						}
					} else {
						$head_display = $v['head'];
					}

					if ($debug_field == 1) {
						$a = '';
						if ($basics['custom_search_result'][$k]) {
							$a = '*';
						}
						$head_display = $a . $head_display . '<br/>['.$k.']<br/>#'.$fields[$k]['type'];
					}

					$r_list[$head_display] = '<li>
						<div><img src="im/sort.png" class="move_me" style="cursor: move; padding-top: 3px;" /></div>
						<div style="width: 180px; line-height: 23px;" header="' . $v['head'] . '">' . $head_display . '</div>
						<div style="width: 40px;">
							<p class="input_align_h" style="padding-top: 2px;">
								<input type="checkbox" value="100" name="column_active[' . $k . ']" class="brd0" id="check-column_active-'.$k.'">
								<label for="check-column_active-'.$k.'">&nbsp;</label>
							</p>
						</div>
						<div class="search_result_name" style="width: 180px;">
							' . form_input('header['.$k.']', array('default' => '', 'param1' => 150)) . '&nbsp;
						</div>
						<div class="search_result_options">
							' . gain_entities_search_result_options($k, $v, $basics) . '&nbsp;
						</div>
					</li>';
				}
			}
		}

		if ($r_list) {
			ksort($r_list);
			$r .= implode('', $r_list);
		}
		$r .= '
		</ul>
		</td></tr>
		<tr>
			<td>
				<input style="float: left;" class="btn medium blue awesome" type="button" value="'.msg('restore').'"  onClick="fw_manage_search_result_save(\''.$entity.'\', \''.$_REQUEST['entity_key'].'\', \''.$entity_mod.'\', \''.$_REQUEST['item_id'].'\', \'restore\', \''.$link.'\');"/>
				<input style="float: right;" class="btn medium gray awesome btn-cancel" type="button" value="'.msg('cancel').'"  onClick="closePopup();"/>
				<input style="float: right; margin-right: 5px;" class="btn medium green awesome btn-add" type="button" value="'.msg('opt2').'" onClick="fw_manage_search_result_save(\''.$entity.'\', \''.$_REQUEST['entity_key'].'\', \''.$entity_mod.'\', \''.$_REQUEST['item_id'].'\', \'submit\', \''.$link.'\');"/>
			</td>
		</tr>
		</table>
		</form>
		<script type="text/javascript">
			var notify_click_restore = "'.msg('notify_click_restore').'";
			$(document).ready(function(){
				gain_ul_effect("fw_manage_search_result_order");
				gain_ul_effect("fw_manage_search_result_order2");
				$("#fw_manage_search_result_order").sortable({
					connectWith: "#fw_manage_search_result_order2",
					handle: $("img.move_me"),
					update : function (event, ui) {
						if (ui.item.parent().attr("id") == "fw_manage_search_result_order") {
							ui.item.find("input[id^=check-column_active-]").click();
							ui.item.find("input[id^=check-column_active-]").attr("checked", true);
						}
					}
				});
				$("#fw_manage_search_result_order2").sortable({
					connectWith: "#fw_manage_search_result_order",
					handle: $("img.move_me"),
					update : function (event, ui) {
						if (ui.item.parent().attr("id") == "fw_manage_search_result_order2") {
							ui.item.find("input[id^=check-column_active-]").attr("checked", false);
						} else {
							ui.item.find("input[id^=check-column_active-]").attr("checked", true);
						}
					}
				});
				$("input[id^=check-column_active]").click(function(){
					if ($(this).attr("checked") == true || $(this).attr("checked") == "checked") {
						$(this).parent().parent().next().find("input").val($(this).parent().parent().prev().attr("header"));
					}
				});
			});
		</script>';
	} else {
		$r .= fw_notify_msg('need to create group');
	}

	$r .= '</div>';
	return $r;
}

function gain_entities_search_result_options($key, $inf, &$basics, $param = '') {
	global $kz;
	$option_display_show = '';

	if ($inf['type'] && !$basics['custom_search_result'][$key]['search_result']) {
		//TODO get default
		if ($inf['type'] == 'E') {
			$fn_options_display = PREFIX . $key;
		} else {
			$fn_options_display = 'form_' . $inf['type'];
		}

		if (function_exists($fn_options_display)) {
			if ($inf['type'] == 'E') {
				$option_display = $fn_options_display($inf, 'search_result');
			} else {
				$option_display = $fn_options_display($key, $inf, 'search_result');
			}

			if (is_array($option_display)) {
				foreach ($option_display as $kx => $vx) {
					$tmp[$kx] = 1;
					if ($kx == 'cut' || $kx == 'entity_link') {
						$option_display_show .= '<span>' . msg('search_result_cut') . ': </span>';
					} else {
						$option_display_show .= '<span>' . msg('search_result_format') . ': </span>';
					}

					//TODO define other type
					if ($kx == 'cut' || $kx == 'entity_link') {
						if ($param == 1) {
							if ($kx == 'entity_link') {
								if ($inf['advanced_options']['entity_link']) {
									$max = '|max=' . $inf['advanced_options']['entity_link'];
								}
								$option_display_show = '{function|' . $kx . '|^info=' . $key . '|^id='.$basics['key'].'|path='. $inf['link']. $max . '}';
							} else {
								if ($inf['advanced_options'][$kx] != '') {
									$option_display_show = '{function|'.$kx.'|^info='.$key.'|max='.$inf['advanced_options'][$kx].'}';
								} else {
									$option_display_show = '{entity|'.$key.'}';
								}
							}
						} else {
							//show input field
							$option_display_show .= form_input('search_result_options[' . $key . '][' . $kx . ']', array('default' => $inf['advanced_options'][$kx], 'param1' => 93));
						}
					} else {
						if ($param == 1) {
							if ($kx == 'format_date') {
								if ($inf['advanced_options'][$kx] == '') {
									$inf['advanced_options'][$kx] = $_SESSION[SESSION_A]['format_date'];
								}

								$option_display_show = '{function|'.$kx.'|^date='.$key.'|format='.$inf['advanced_options'][$kx].'}';
							} else if ($kx == 'format_money') {
								if ($inf['advanced_options'][$kx] != '') {
									if (strstr($inf['advanced_options'][$kx], 'C')) {
										$currency_field = '|^currency='.$key.'_currency';
									}
									if (strstr($inf['advanced_options'][$kx], 'K')) {
										$thousands_field = '|thousands=1';
									}
									$option_display_show = '{function|'.$kx.'|^value='.$key.$currency_field.$thousands_field.'}';
								} else {
									$option_display_show = '{entity|'.$key.'}';
								}
							} else if ($kx == 'user_name') {
								if ($inf['advanced_options'][$kx] == '') {
									$inf['advanced_options'][$kx] = 'abbr';
								}

								if ($inf['advanced_options'][$kx] == 'full') {
									$h = 'firstname';
								} else {
									$h = $inf['advanced_options'][$kx];
								}

								$option_display_show = '{function|'.$kx.'|^id='.$key.'|style='.$inf['advanced_options'][$kx].'}';

								$basics['sql_query_add_table'][] = 'gain_user AS a'.(++$kz);
								$basics['sql_query_add_condition'][] = 'a'.$kz.'.id_user=' . $basics['table'] . '.' . $key;

								$basics['replace_h'][$key] = 'a'.$kz.'.' . $h;
							} else if ($kx == 'entity') {
								if (!$inf['advanced_options'][$kx]) {
									$inf['advanced_options'][$kx] = 'detail_link';
								}

								if ($inf['advanced_options']['cut']) {
									$max = '|max=' . $inf['advanced_options']['cut'];
								}

								$option_display_show = '{function|' . $kx . '|^info=' . $key . '|key=' . $inf['entity_id'] . '|table='.$inf['entity_table'] . '|entity=' . $inf['entity'] . '|display=' . $inf['advanced_options'][$kx] . $max . '}';
								$fields_select = gain_entity_get_entity_detail($inf['entity']);
								$basics['replace_h'][$key] = PREFIX . $fields_select['table_name'] . '.' . $fields_select['field_select'];
							}
						} else {
							$option_display_show .= form_select('search_result_options[' . $key . '][' . $kx . ']', array('default' => $inf['advanced_options'][$kx], 'values' => $vx, 'param1' => 150, 'req' => 1));
							if ($kx == 'entity') {
								$option_display_show .= ' <span>' . msg('search_result_cut') . ': </span>' . form_input('search_result_options[' . $key . '][cut]', array('default' => $inf['advanced_options']['cut'], 'param1' => 100));
							}
						}
					}
				}
			}
		}
	}

	return $option_display_show;
}

function gain_entities_search_result_default($basics, $fields, $id_user = 0){
	global $db;
	if ($basics['default_search_result']) {
		foreach ($basics['default_search_result'] as $k => $f) {
			$header_def = '';
			$width = '';
			if ($basics['custom_search_result'][$f]['header_def']) {
				$header_def = $basics['custom_search_result'][$f]['header_def'];
			}

			if ($basics['custom_search_result'][$f]['width']) {
				$width = $basics['custom_search_result'][$f]['width'];
			}

			$param_qry = array(
				'table' => 'gain_fw_search_result',
				'cols' => array(
					'entity', '%s', $basics['entity'],
		    		'id_user', '%d', $id_user,
					'field_name', '%s', $f,
					'header', '%s', $header_def,
					'field_width', '%s', $width,
					'sort_field', '%d', $k,
				),
			);

			if ($id_user > 0) {
				$param_qry['cols'][] = 'entity_key';
				$param_qry['cols'][] = '%s';
				$param_qry['cols'][] = $basics['entity_key'];

				//field_name, header, field_width, advanced_options
				$rsl[$f]['header'] = $header_def;
				$rsl[$f]['field_width'] = $width;
				$rsl[$f]['sort_field'] = $k;
				if ($_REQUEST['mod'] != 'dashboard') {
					db_query($param_qry);
				}
			}
		}
	} else {
		foreach ($fields as $f => $v) {
			if ($v['skip'] != 1 && ($v['type'] != 'file' && $v['type'] != 'head') && ($f != 'added' && $f != 'added_by' && $f != 'updated' && $f != 'updated_by' && $f != 'phone_number') && $v['search_result'] != 1) {
				$header_def = '';
				$v['head'] = strip_tags($v['head']);
				if ($v['vhead']) {
					if (is_array($v['vhead'])) {
						$header_def = implode(',', $v['vhead']);
					} else {
						$header_def = $v['vhead'];
					}
				} else {
					$header_def = $v['head'];
				}
				
				$width = '';
				if ($basics['custom_search_result'][$f]['header_def']) {
					$header_def = $basics['custom_search_result'][$f]['header_def'];
				}
				if ($basics['custom_search_result'][$f]['width']) {
					$width = $basics['custom_search_result'][$f]['width'];
				}
				$order = ++$kx;
				$param_qry = array(
					'table' => 'gain_fw_search_result',
					'cols' => array(
						'entity', '%s', $basics['entity'],
			    		'id_user', '%d', $id_user,
						'field_name', '%s', $f,
						'header', '%s', $header_def,
						'field_width', '%s', $width,
						'sort_field', '%d', $order,
					),
				);

				if ($id_user > 0) {
					$param_qry['cols'][] = 'entity_key';
					$param_qry['cols'][] = '%s';
					$param_qry['cols'][] = $basics['entity_key'];

					//field_name, header, field_width, advanced_options
					$rsl[$f]['header'] = $header_def;
					$rsl[$f]['field_width'] = $width;
					$rsl[$f]['sort_field'] = $order;
					if ($_REQUEST['mod'] != 'dashboard') {
						db_query($param_qry);
					}
				}
			}
		}
	}
	if ($id_user > 0) {
		return $rsl;
	}
}

function gain_entities_search_result_get($entity_key, &$basics, $fields, &$table, $param = '') {
	global $db, $cm_menu;

	$cleanVar = fw_data_cleanup($fields, $basics);
	$fields  = $cleanVar[0];
	$basics  = $cleanVar[1];

	//more fields
	gain_entities_search_result_fields($fields);

//	if ($_REQUEST['mod'] != 'dashboard') {
//		gain_entities_search_result_default($basics, $fields);
//	}
	//TODO
	$entity_mod = $_REQUEST['mod'];
	if ($entity != $entity_mod && $entity_mod != 'settings' && $entity_mod != 'newsletter' && $_REQUEST['item_id'] && $entity_mod != 'entities' && $entity_mod != '') {
		//$entity_key .= '_' . $_REQUEST['mod'];
	}
// 	if (($cm_menu['M'][$basics['entity']]['M'] != $_REQUEST['mod'] && $_REQUEST['mod'] != 'entities' && $_REQUEST['mod'] != '' && $_REQUEST['mod'] != 'dashboard' && $_REQUEST['mod'] != $basics['entity'] && $_REQUEST['mod'] != 'settings' && $_REQUEST['mod'] != 'newsletter') || $_REQUEST['item_id']) {
// 		$entity_key .= '_' . $_REQUEST['mod'];
// 	}
	if ($_REQUEST['mod'] != 'dashboard') {
		//get field for current user
		$sql = SQL('SELECT field_name, header, field_width, sort_field, advanced_options
		FROM gain_fw_search_result
		WHERE entity=%s
		AND entity_key=%s
		AND id_user=%d
		ORDER BY sort_field ASC', $basics['entity'], $entity_key, $_SESSION[SESSION_L]);
		$rsl = $db->GetAssoc($sql);
	}

	if (!$rsl) {
		$basics['entity_key'] = $entity_key;
		$rsl = gain_entities_search_result_default($basics, $fields, $_SESSION[SESSION_L]);
	}

	if ($rsl) {
		foreach ($rsl as $k => $v) {
			$t[$k]['width'] = $v['field_width'];
			$t[$k]['header_def'] = $v['header'];
			$t[$k]['sort_field'] = $v['sort_field'];
			$t[$k]['advanced_options'] = unserialize($v['advanced_options']);
		}
	}

	if ($param == 1) {
		return $t;
	}
	$table['headers2']['info'] = $t;
	gain_entities_search_result_clean($basics, $fields, $table);
}

function gain_entities_search_result_clean(&$basics, $fields, &$table){
	//default for width of each column to 100 only options set to 60
	//:h
	//:width
	//:header_def
	//:search_result
	if (!$basics['resize_table']) {
		$table['headers2']['table'] = '100%';
	}
	if ($table['headers2']['info']) {
		//define by php
		$search_result = $basics['custom_search_result'];

		//define by database
		foreach ($table['headers2']['info'] as $k => $v) {
			unset($table['headers2']['info'][$k]);
			//h
			//width
			//search_result
			//header_def
			if ($v['width'] == '') {
				if ($basics['resize_table']) {
					$table['headers2']['info'][$k]['width'] = '100';
				}
			} else {
				//1: user define
				//2: system define
				if ($v['width']) {
					$table['headers2']['info'][$k]['width'] = $v['width'];
				} else {
					$table['headers2']['info'][$k]['width'] = $search_result[$k]['width'];
				}
			}

			$table['headers2']['info'][$k]['h'] = $v['h'];
			if ($v['h'] == '') {
				if (substr($k, 0,2) != 's_') {
					$table['headers2']['info'][$k]['h'] = $basics['table'] . '.' . $k;
					if ($search_result[$k]['h']) {
						$table['headers2']['info'][$k]['h'] = $search_result[$k]['h'];
					}
				} else {
					$table['headers2']['info'][$k]['h'] = $k;
				}
			}

			//set header def from
			//1: user define
			//2: system define
			//3: fields define
			if ($v['header_def'] == '') {
				if ($search_result[$k]['header_def'] != '') {
					$table['headers2']['info'][$k]['header_def'] = $search_result[$k]['header_def'];
				} else {
					$table['headers2']['info'][$k]['header_def'] = $fields[$k]['head'];
				}
			} else {
				$table['headers2']['info'][$k]['header_def'] = $v['header_def'];
			}

			//set pattern
			//1: system define
			//2: user define
			//echo $k.'|'.$search_result[$k]['search_result']."<br/>";
			if ($search_result[$k]['search_result']) {
				$table['headers2']['info'][$k]['search_result'] = $search_result[$k]['search_result'];
			} else {
				if ($fields[$k]['primary_field'] == 1) {
					//set link
					//
					if (is_array($v['advanced_options'])) {
						$fields[$k]['advanced_options'] = $v['advanced_options'];
						$txt = gain_entities_search_result_options($k, $fields[$k], $basics, 1);
					} else {
						$txt = '{entity|' . $k . '}';
					}
					
					$table['headers2']['info'][$k]['search_result'] = '<a href="index.php?mod=' . $basics['op'] . '&link=detail&id={entity|'.$basics['key'].'}">'.$txt.'</a>';
				} else {
					//set default options for other type
					if (!$v['advanced_options']) {
						if ($fields[$k]['type'] == 'user' || ($fields[$k]['entity'] != '' && $fields[$k]['type'] == 'E') || $fields[$k]['type'] == 'date') {
							$v['advanced_options'] = array();
						}
					}

					if (is_array($v['advanced_options'])) {
						$fields[$k]['advanced_options'] = $v['advanced_options'];
						$table['headers2']['info'][$k]['search_result'] = gain_entities_search_result_options($k, $fields[$k], $basics, 1);
					} else {
						if ($fields[$k]['type'] == 'E') {
							$table['headers2']['info'][$k]['search_result'] = '{function|' . $k . '}';
						} else {
							$table['headers2']['info'][$k]['search_result'] = '{entity|' . $k . '}';
						}
					}
				}
			}

			if ($basics['replace_h'][$k]) {
				$table['headers2']['info'][$k]['h'] = $basics['replace_h'][$k];
			}
		}
		unset($search_result[$k]);
	}

	if ($search_result) {
		foreach ($search_result as $k => $v) {
			if (!$table['headers2']['info'][$k] && ($k == 'options' || $k == 's_icon')) {
				$table['headers2']['info'][$k]['width'] = $v['width'];
				$table['headers2']['info'][$k]['header_def'] = $v['header_def'];
			}
		}
	}
}

function gain_entities_get_entity_icon($entity){
	$entity_info = gain_entity_get_entity_detail($entity);
	if ($entity_info['icon']) {
		return '<img src="files/note/entity/'.$entity_info['table_name'].'.'.$entity_info['icon'].'" title="'.msg($entity).'"/>';
	}
}

function gain_entities_duplicate_checked(){
	global $db;
	$entity = $_POST['entity'];
	$entity_field = $_POST['entity_field'];
	$entity_inf = gain_entity_get_entity_detail($entity);
	if ($_POST['entity_id']) {
		$sql_add = SQL(' AND ' . $entity_inf['key'] . '!=%d', $_POST['entity_id']);
	}
	
	if ($_REQUEST['entity_name_first'] || $_REQUEST['entity_name_last']) {
		$sql = SQL('SELECT GROUP_CONCAT(' . $entity_inf['field_id'] . ')
		FROM ' . PREFIX . $entity_inf['table_name'] . '
		WHERE ' . $entity_field . '_first=%s
		AND ' . $entity_field . '_last=%s
		AND removed IS NULL' . $sql_add, $_POST['entity_name_first'], $_POST['entity_name_last']);
		$id = $db->GetOne($sql);
	} else if ($_POST['entity_name']) {
		$sql = SQL('SELECT GROUP_CONCAT(' . $entity_inf['field_id'] . ')
		FROM ' . PREFIX . $entity_inf['table_name'] . '
		WHERE ' . $entity_field . '=%s
		AND removed IS NULL' . $sql_add, $_POST['entity_name']);
		$id = $db->GetOne($sql);
	}

	if ($id) {
		$duplicate_word = fw_notify_msg('duplicate_details', 'error', array('style' => 'margin-top: 5px;', 'close_element' => 0));
		$r = str_replace('{check details}', '<a href="#click_detail'.$id.'" onclick="show_popup_link(this,\'ajax=1&mod='.$entity.'&view=detail&id='.$id.'\',0);"><strong>'.msg('show details').'</strong></a>', $duplicate_word);
	}

	echo $r;
}

function gain_entities_login_tip(){
	global $db, $dd;
	//update value tip in gain_user when click "close"
	if ($_REQUEST['tip']) {
		if ($_REQUEST['tip'] == "true") {
			$get_tip = "Y";
		} else {
			$get_tip = "N";
		}
		$sql = 'UPDATE gain_user SET tip="'.$get_tip.'"
		WHERE id_user='.$_SESSION[SESSION_L];

		$db -> Execute($sql);
		exit;
	}
	
	if (!$dd['login_tip']) {
		$sql = 'SELECT id_tip, tip_name, tip_content
		FROM gain_tip
		WHERE removed IS NULL';
		$dd['login_tip'] = $db->GetArray($sql);
		$dd['login_tip_cnt'] = count($dd['login_tip']);
		$dd['login_tip'][$dd['login_tip_cnt']] = $dd['login_tip'][0];
	}

	//first open, get random tip
	if (!isset($_REQUEST['id_tip'])) {
		$id_tip = rand(0, ($dd['login_tip_cnt']-1));
	} else {
		$id_tip = $_REQUEST['id_tip'];
	}

	$tip_info = $dd['login_tip'][$id_tip];
	
	$r = '<div class="popupHeader">'.$tip_info['tip_name'].'</div>
	<div id="tip_content" style="padding: 15px 0;">
				<div style="padding: 5px 15px 20px 0px;">'.$tip_info['tip_content'].'</div>
				<form style="margin-left: 10px;">
					<p class="input_align_v"><input type="checkbox" checked="" value="Y" name="tip"> <label>show login tips</label> </p>
				</form>
				<div style="float: left;"><input style="margin: auto;" type="button" value="'.msg('<< previous tip').'" name="opt1" class="btn medium blue awesome" onclick="previous_tip('.$id_tip.', '.$dd['login_tip_cnt'].');"></div>
				<div style="float: left; margin: 0px 5px;"><input style="margin: auto;" type="button" value="'.msg('next tip >>').'" name="opt1" class="btn medium blue awesome" onclick="next_tip('.$id_tip.', '.$dd['login_tip_cnt'].');"></div>
				<div style="float: left; padding-bottom: 15px;"><input style="margin: auto;" type="button" value="'.msg('close').'" name="opt1" class="btn medium green awesome btn-add" onclick="close_tip();"></div>
		</div>
		<script type="text/javascript">
			$(document).ready(function(){
				$("div.ui-dialog-title").html("'.$tip_info['tip_name'].'");
			});
		</script>';	
	return $r;
}

function gain_quick_search_list(){
	global $db;

	$sql = SQL('SELECT entity, fields, 1
	FROM gain_user_quick_search
	WHERE id_user=%d
	ORDER BY entity', $_SESSION[SESSION_L]);
	$rsl = multiAssoc($db->GetArray($sql));
	//$_POST['searchInfo']
	$param = quick_search_param();

	$r = '<div class="popupHeader">'.msg('result').'</div>';
	if ($rsl) {
		foreach ($param as $entity => $inf) {
			if ($inf) {
				foreach ($inf as $k => $v) {
					$pattern = strtolower(msg('quick_search_' . $entity) . ' ' . $param[$entity][$k]);
					if (strstr(strtolower(trim($_POST['searchInfo'])), $pattern)) {
						unset($rsl);
						$rsl = array($entity => array($k => 1));
						$_POST['searchInfo'] = str_replace($pattern, '', strtolower(trim($_POST['searchInfo'])));
					}
				}
			}
		}

		$all = 0;
		foreach ($rsl as $entity => $inf) {
			//display entity
			//gain
			require_once(PATH.'modules/'.$entity.'.php');
			$fn = PREFIX . $entity . '_quick_search';

			$en_display = $_SESSION[SESSION_A]['quick_search'];
			if ($en_display[$entity] == 1 || !isset($en_display[$entity])) {
				$rsl_style = '';
				$rel = 1;
				$rsl_im = 'ui-icon-minusthick';
				$title = msg('collapse');
			} else {
				$rsl_style = 'display: none;';
				$rel = 0;
				$rsl_im = 'ui-icon-plusthick';
				$title = msg('expand');
			}

			$per_page = 15;
			$j = '';
			$rsl_num = 0;
			if (function_exists($fn)) {
				$content = $fn($_POST['searchInfo'], $inf, $per_page);
				$j = $content[0];
				$rsl_num = $content[1];
				$all += $rsl_num; 
			}

			if (!$_REQUEST['entity']) {
				$r .= '<div style="cursor: pointer; padding: 4px 0; width: 100%;" id="'.$entity.'_qs_header" rel="'.$entity.'" class="ui-state-default ui-corner-all" onclick="displayQS(\''.$entity.'\');">
					<span style="float: left; margin: 0 5px;" title="'.$title.'" class="ui-icon '.$rsl_im.'"></span> <strong style="vertical-align: top;">'. msg('menu_'. $entity).'(' . $rsl_num . ')</strong>  <img src="im/remove.png" style="float: right; z-index: 1000;" title="'.msg('remove quick search entity').'" class="fw-point '.$entity.'_remove_icon hide" onclick="quick_search_entity_remove(\''.$entity.'\');"/></div>';
			}

			$r .= '<div style="'.$rsl_style.'; padding-top: 4px; padding-bottom: 2px;" id="'.$entity.'_qs_rsl" rel="'.$rel.'">';
			$r .= $j;

			if (isset($_REQUEST['p'])) {
				$p = $_REQUEST['p'] + 1;
				$per_page_sum = $per_page*$p;
			} else {
				$p = 1;
				$per_page_sum = $per_page;
			}

			if ($rsl_num > $per_page_sum && $_REQUEST['p'] != 'all') {
				$more_link = '<div style="float: right;"><a href="#records" onclick="qsearch_more(\''.$entity.'_qs_rsl\', \''. $n .'\',\'' . $entity . '\', \'' . $_POST['searchInfo'] . '\', '.$p.');">'. msg('show_another') .'</a> | <a href="#ShowAllQS" onclick="qs_show_all(\''.$entity.'_qs_rsl\',\'' . $entity . '\', \'' . $_POST['searchInfo'] . '\');">' . msg('all') . '</a></div><br style="clear: both;"/>';
				$r .= $more_link;
			}

			if ($_REQUEST['p'] && $_REQUEST['entity'] == $entity) {
				return $j . $more_link;
			}
			$r .= '</div>';	
		}
	}

	if ($all == 0) {
		$content = msg('not match quick search');
		$content = str_replace('{{click}}', '<a href="#profile" onclick="$(\'#quickSearchquick_search\').val(\'\'); show_popup_link(this, \'&ajax=1&mod=profile&quick_search=user_search\', 1, 660);">'.msg('click here').'</a>', $content);
		$r = '<div class="popupHeader">'.msg('result').'</div>' . $content;
	}
	
	$r .= '
	<script type="text/javascript">
		function quick_search_entity_remove(entity){
			$("#"+entity+"_qs_rsl").remove();
			$("#"+entity+"_qs_header").remove();
			$.get("index.php?ajax=1&mod=profile&entity_remove="+entity);
		}

		$(document).ready(function(){
			$("div[id$=_qs_header]").mouseover(function(){
				$("img."+$(this).attr("rel")+"_remove_icon").show();
			}).mouseout(function(){
				$("img."+$(this).attr("rel")+"_remove_icon").hide();
			});

			// archive mail icon init
			entity_tool_box_ready();
		});
	</script>';

	return $r;
}

function gain_quick_search_phone($search, $entity){
	global $db;
	$entity_details = gain_entity_get_entity_detail($entity);
	
	$phone_search_key = str_replace(array('*', '?'),array('%', ''), trim($search));

	if ($phone_search_key{0} == 0) {
		$phone_search_key = substr($phone_search_key, 1, strlen($phone_search_key));
	}
	
	#check phone search
	if ($phone_search_key != '') {
		$sql = 'SELECT DISTINCT(p.id_entity)
		FROM gain_phone_entity AS p, gain_'.$entity_details['table_name'].' AS e
		WHERE p.entity="'.$entity_details['table_name'].'" 
		AND e.'.$entity_details['field_id'].'=p.id_entity 
		AND e.removed IS NULL';
		$sql .= ' AND (p.phone_no_search LIKE "%'.$phone_search_key.'%")';
		$phone_id_entity = $db->GetCol($sql);
		if ($phone_id_entity) {
			$phone_sql = $entity_details['field_id'].' IN ('.implode(',', $phone_id_entity).')';
			return $phone_sql;
		}
	}
}
?>